Advertisement

Random Numbers?

Started by March 09, 2003 06:15 PM
3 comments, last by Nefrugle 21 years, 8 months ago
Hello, I don''t quite understand the srand() and rand() functions. I want a random number between 1 and 10 but it''s not working and keeps giving me the same exact number. could someone help explain this to me. Thanks for your help.
-- NeFrUgLe
I think it''s something like this:


  srand(time(NULL); //seeds random generator with timecout>>rand()%10+1; //+1; otherwise it will give you 0-9  


The trick is to see with srand before trying to call rand()

Peon
Peon
Advertisement
"srand" seeds the random number generator. Otherwise you would get the same numbers each time you ran the program. In Peon''s example he seeded it with the system time. This way you will get different random numbers on each run. You could also seed it with a specific number if you wanted to generate the same set of numbers for testing. You only need one "srand" line in your entire program, usually at the beginning.

"rand" is what actually generates the number.
Thank you guys for all your help with my little problem.
-- NeFrUgLe
Directly from the manpage for rand():
In Numerical Recipes in C: The Art of Scientific Computing (William  H.       Press, Brian P. Flannery, Saul A. Teukolsky, William T. Vetterling; New       York: Cambridge University Press, 1992 (2nd ed., p. 277)), the  follow‐       ing comments are made:              "If  you want to generate a random integer between 1 and 10, you              should always do it by using high‐order bits, as in                     j=1+(int) (10.0*rand()/(RAND_MAX+1.0));              and never by anything resembling                     j=1+(rand() % 10);              (which uses lower‐order bits)." 

This topic is closed to new replies.

Advertisement