• Popular Now

• 12
• 11
• 9
• 10
• 13

Archived

This topic is now archived and is closed to further replies.

Random numbers!

This topic is 5186 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi, im trying to learn C for a while now and im not getting more motivated by this, it''s so damn huge that language, it''s confusing me. anyway, how do i make a random number in C... not c++ for as far as i know its int X = rand(1..9); but that''s not working and i can''t find it anywhere. Galo

Share on other sites
I think its
int x = rand() % y;
where y is how many different numbers you want.

Oh, and if you want a number between 1 and 10 its rand() % 10+1, because it starts counting from zero.

[edited by - Bjorta on January 7, 2004 1:09:07 PM]

Share on other sites
The suggestion

int x = rand() % y;

will work well enough, but it''s distribution isn''t usually even, if that''s a concern. To get a more evenly distributed random number, here''s two simple functions (one for ints, and one for doubles):

int Random(int Min, int Max){  return (int)((Max - Min + 1) * (double)rand()               / ((double)RAND_MAX + 1.0) + Min);}double Random(double Min, double Max){  return (Max - Min) * (double)rand() / (double)RAND_MAX + Min;}

Share on other sites
You need stdlib.h for rand() to work.

[edited by - furby100 on January 7, 2004 3:49:10 PM]

Share on other sites
and don''t forget to seed it at the start of the program (call srand and send it the current time), or else you''ll get the same sequence of numbers every time.

Share on other sites
quote:
Original post by Anonymous Poster
and don''t forget to seed it at the start of the program (call srand and send it the current time), or else you''ll get the same sequence of numbers every time.

Whats Seeding ?

anaaahhh "You need stdlib.h for rand() to work." you mean stdio.h ?

galo

Share on other sites
Nah he means stdlib.h

Since there is no such thing as complete randomness the computer must have a starting psuedo-random value... this is called the seed

cstdlib

Share on other sites
#include"iostream.h"
#include"stdlib.h"
#include"time.h"

int main()
{
//declare variables
int die_sides, rollnum;
//set seed
srand(time(0));
//ask for user input (don't have to its optional)
cout<<"Enter a number sided die";
cin>>die_sides;

//use random function
rollnum = rand()%die_sides;
cout< getch();
return 0;
}
you can replace die_sides with any number and you may do math to add minimums and maximums like so:
rollnum = rand()%monster_dmg+55;

[edited by - Thamior on January 8, 2004 1:39:58 PM]

Share on other sites
...

C++ is a better C, you know - much better.

You''d be surprised at how much more you can do with C++ (or atleast more efficiently, in a faster way).

Learn C++, there is no reason for you to learn C - you are not gaining anything but losing.

Peace.