Random Numbers?
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:
The trick is to see with srand before trying to call rand()
Peon
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
"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.
"rand" is what actually generates the number.
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
Popular Topics
Advertisement