1

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?

Community
  • 1
  • 1
William
  • 1,837
  • 2
  • 22
  • 36

2 Answers2

4

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.

p1100i
  • 3,710
  • 2
  • 29
  • 45
  • 2
    cplusplus.com is not only not official, it contains many errors and is thus not well regarded here. Try [cppreference.com](http://en.cppreference.com/w/), they try to adhere to the actual standard. –  Oct 15 '12 at 16:39
  • Modified it accordingly, thx. – p1100i Oct 15 '12 at 17:23
0

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

BigBoss
  • 6,904
  • 2
  • 23
  • 38