View Full Version : rand() in C
kozumo
07-03-2002, 01:39 AM
I was playing around with the rand() function to generate random numbers in C and when I ran it, it'd give me a series of random numbers and every other time I'd run it, it'd still give me the same series until I modified the code (like changing the value of LIMIT).
I don't understand why it gives the same series. Shouldn't it give a different series everytime the program runs?
#include <stdio.h>
#include <stdlib.h>
#define LIMIT 10
int main()
{
int i = rand() % LIMIT;
int j = 0;
for (j = 0; j < LIMIT; j++, i = rand() % LIMIT)
printf("%d\n", i);
return 0;
}
{F}allen
07-03-2002, 02:06 AM
include time, then use:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LIMIT 10
int main()
{
srand((unsigned)time(NULL));
for (int j = 0; j < 10; j++)
{
int i = rand() % LIMIT;
printf("%d\n", i);
}
return 0;
}
edit: example didn't include time =D
not sure if the int i = rand() ... is the right way to get a random int, but that should be easy enough. The srand() call sets the random seed to be the timestamp at runtime is called, and is therefore different every time.
sicarius
07-03-2002, 02:31 AM
What {F}allen gave you is correct. I just wanted to put in more of a "why" it was correct. As you said when you call rand() it gives a series of numbers, then when you restart the program it will give you the exact same series. This is because the rand() function really isn't random at all. This may sound confusing at first, but here is what is going on:
First of all the rand() function simply returns a number based on a mathmatical formual, using a number called the "seed" as its input. Just for the sake of argument lets say that the formula was something like: ((seed + 32) / 12) * 4
After computing this value, the result is saved and used as the seed value for the next time that you call rand(). So by calling rand() over and over with the same seed, you get the same numbers.
What {F}allen did is the most common fix. Call the srand function with current time as the argument. This makes sure that every time your program starts you will have a different starting seed. You do not, however, have to call the srand function every time you want a "random" number. You should only call it once prior to your first call to the rand function.
kozumo
07-03-2002, 03:19 AM
Thanks {F}allen for your example and thanks sicarius for your explanation. That was really helpful, guys ;)
Yeah I read the man page for rand and srand, but they didn't explain what 'seed' was.
vBulletin® v3.7.0, Copyright ©2000-2009, Jelsoft Enterprises Ltd.