Possible Duplicate:
Recommended way to initialize srand?
I have the following problem when using srand() in c.
I call srand(time(NULL)) in a loop, but the loop finishes before 1 sec and every time I call the rand() I get the same value.
How can I solve this?
I found the answer with your help.
srand
's purpose is to initialize the random number generator.Its parameter is called a seed. If you give the same seed twice, you can expect the random number generator (subsequent calls to
rand()
) to return the same sequence of "random" numbers.In your case you're constantly calling srand with the same value (until the second changes), so rand() will always return you the same value.
You just need to call
srand
once.Why are you calling
srand
in a loop? Just call it once at the start of your program and then callrand
any number of times.You just need to initialize
srand()
once, then you just need to userand()
to generate the random numbers. And to generate random numbers use Better random algorithm?Don't call srand in the loop. Why are you doing this?
Just initialize it outside the loop, once.
because the seed is bound into the time() which are seconds since unix epoch, basically you're giving it the same seed because the loop takes less than a second.
What you should do is get the time in microseconds. Take a look at gettimeofday() if you're coding for windows google microseconds win32 C, you mind need to convert it from double to integerso just do this (unsigned int)double * 100.0f;