rand() and srand(seed)

Posted By: sheefo

rand() and srand(seed) - 03/05/07 13:13

I do not understand the concept of srand. I am using "rand() % 100 + 1" to generate a random number in a range of 1 to 100. Each time I do so it generates the same "random" number, so I guess it is not random then.

Do I use srand to sort this out? What does srand do? I need an explination, not a direction to a C++ reference (they do me no good on this subject).
Posted By: DGuy

Re: rand() and srand(seed) - 03/06/07 03:22

srand() "seeds" the random number generator (i.e. rand()).

If you call srand(100), then call rand() 10 times, then call srand(100), then finally call rand() 10 more times, you'll get the same set of 10 random numbers both times.

The reason you are getting the same "random" numbers is probably because the "seed" number is always the same at program start.

To get different random number each run, try srand(GetTickCount())

GetTickCount() returns the number of millisecs since the computer started.

HTH
Posted By: sheefo

Re: rand() and srand(seed) - 03/06/07 09:24

Thank you. It works now. Your explanation was better than any C++ reference I found. I use http://www.cplusplus.com/

I always thought that "random" meant random in programming. Apparently there just the same sequence of numbers.
Posted By: Joey

Re: rand() and srand(seed) - 03/06/07 19:58

well, of the generator. you should also be cautious with utilizations like these:
rand()%40000, because RAND_MAX is often defined as 65535, so in this case you'll get the numbers between 0 and 25535 twice as often as the ones above this interval.
© 2023 lite-C Forums