0

Possible Duplicate:
how to generate different random number in a loop in C++?

In this code:

int Randtest(int len)
{
    int test[100]={};
    for(int i=0;i<len;i++)
    {
        srand ( time(NULL) );
        cout <<(test[i]=rand()%10);
    }
}

int main()
{
 Randtest(8);
}

The output will always be a sequence of repeated numbers, like 22222222 or 11111111. How do I make it produce eight random numbers?

Community
  • 1
  • 1
Abanoub
  • 3,623
  • 16
  • 66
  • 104

3 Answers3

6

The problem with your code is here:

for(int i=0;i<len;i++)
{
    srand ( time(NULL) );
    cout <<(test[i]=rand()%10);
}

The issue is that on each iteration of the loop, you're reseeding the randomizer with the current system time, usually measured at second precision. Every time you provide a seed to the randomizer it resets the sequence of random values that gets handed back, and so if you keep seeding the randomizer with the same value over and over and then only call rand once every time you reseed it, you'll get back the same random number sequence over and over again. Since the system time only changes once a second, this will produce the same sequence of numbers repeatedly.

To fix this, move the call to srand out of the loop, as seen here:

srand ( time(NULL) );
for(int i=0;i<len;i++)
{
    cout <<(test[i]=rand()%10);
}

This way, you only seed the randomizer once, and so your sequence should look more pseudorandom. You may still see some duplicate values, but that will be due to chance rather than the random number generator acting deterministically.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
2

srand starts the random number generator at the current time, given by time(NULL).

Your loop runs so fast that the time doesn't change each pass through the loop, and you keep resetting your Random Number generator to the same starting point.

Answer: Use srand ONCE and only once, outside the loop.

abelenky
  • 63,815
  • 23
  • 109
  • 159
0

Quit re-seeding with the same value on every iteration of the loop. Just do it in main.

eduffy
  • 39,140
  • 13
  • 95
  • 92