Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

c++ random numbers srand [duplicate]

Writer Olivia Zamora

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?

5

2 Answers

Your problem is about seeding the random number generator with the same value. The srand function 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 rand function without arguments, and it will generate random numbers. For example:

 /* initialize random seed with actual date-time */ std::srand(std::time(NULL)); /* generate ten random number lower than 10 */ int random, times = 10; while(times){ random = std::rand() % 10; times--; }

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.

2

rand function is not very good at generating random numbers, take a look at boost::random. it is awesome and can create random and semi random numbers