random

Started by
2 comments, last by gamesrme 22 years, 2 months ago
I am using this: code starts here //////////////////////////////////// /////////////////////////// #include #include #include void main() { for(int j=0; j<10; j++) { srand((unsigned int) time(0)); int i = rand() % 100; // random number between 0 and 99 int j = rand() % 5; // random number between 0 and 4 cout<<i<<" "<<j<<"\n"; } } /////////////////////////// code ends here for make random numbers, it makes random numbers alright every time you run the program, but every time you call the function it gives the same random number each time. I need a different random number every time I run the program AND every time I call the function. could some one please help!
Advertisement
Move the call to srand out of the loop; do it right before the loop. What is happening is that the program is executing very quickly, and you''re calling srand with the same number (time(0) is returning the same number). That resets the random number generator back to the same initial seed, yielding the same stream of random numbers.
or replace srand();

with

srand(GetTickCount());
quote:or replace srand();

with

srand(GetTickCount());


It would still be better to just move the call out of the loop. Even with GetTickCount() you''ll still probably get the same values (if your loop runs fast enough).

This topic is closed to new replies.

Advertisement