Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with rand() and srand() please :) 1

Status
Not open for further replies.

MikeBronner

Programmer
May 9, 2001
756
US
I'm having the problem when using the following code, that it creates the same number, instead of different random numbers:

for (int i=0; i<10; i++)
{
srand((unsigned) time(NULL));
int nRandNum = rand() % (nMaxNum - nMinNum + 1) + nMinNum;
}

Could anyone PLEASE help me out with a workaround to return random numbers? Thanks ;-)

Mike B. Take Care,
Mike
 
You should use srand() only once, in this case probably right before the for loop. srand() sets the starting point for rand(). Once a starting point is selected, you can use rand() alone to give a sequence of numbers.

Your problem comes to this: your loop gets executed very fast (in certainly less than a second), so using srand(timer(NULL)) before each call to rand() means to reset the sequence always to the same number.

Vincent
 
Is there a way to specify time in milliseconds, instead of seconds? The reason being that I need to make many random numbers off of different seeds in a small period of time.
Thanks ;-) Take Care,
Mike
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top