Thursday, July 9, 2009

C++ Help! I get the same random number every time I seed it with time?

Well, I have a loop and seed the generator like this:





srand(time(NULL))


cout %26lt;%26lt; rand();





And I get the same number every loop.


I even checked the time like this:


cout %26lt;%26lt; time(NULL)





at the beginning and end of my program but still get the same time.





How do I get a truly random number? Is there a more precise time function? Thanks.

C++ Help! I get the same random number every time I seed it with time?
Nope, that's how you do it, something goofy is going on. Have you tried





A) Only seeding it once at the beginning of the program? You only need to seed it once.


B) Printing the integer (or rather time_t object) value to see what time() is returning?
Reply:Make sure you don't repeat srand(time(NULL));





srand(time(NULL));


if (1 == 1) {


cout %26lt;%26lt; rand();


}





You can use your loop of choice, but don't repeat the srand(time(NULL)); function.


No comments:

Post a Comment