C++ Random Numbers Srand [Duplicate]

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

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

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest