Possible Duplicate:
rand function returns same values when called within a single function c++
I have a program which creates a new set of random numbers each mouse click. If I run the program without srand ( time(NULL) ); the numbers are the same each time. If I run the program WITH srand ( time(NULL) ); then it’s possible for me to spam click and the numbers will repeat themselves. How can I get around this?
Your problem is about seeding the random number generator with the same value. The
srandfunction is for initializing the so called “seed” for it. A seed can be used to generate the same random numbers in a sequence.First you need to initialize the generator then just call the
randfunction without arguments, and it will generate random numbers. For example:About the “spam click”:
std::time(NULL)has precision in seconds, so you’re initializing the random seed with the same value if you click within the same second.Here is an example on the official c++ reference site,
and another example on cplusplus.com too.