Same random numbers every loop iteration

When you call srand(x), then the value of x determines the sequence of pseudo-random numbers returned in following calls to rand(), depending entirely on the value of x.

When you’re in a loop and call srand() at the top:

while (...) {
    srand(time(0));
    x = rand();
    y = rand();
}

then the same random number sequence is generated depending on the value that time(0) returns. Since computers are fast and your loop probably runs in less than a second, time(0) returns the same value each time through the loop. So x and y will be the same each iteration.

Instead, you only usually need to call srand() once at the start of your program:

srand(time(0));

while (...) {
    x = rand();
    y = rand();
}

In the above case, x and y will have different values each time through the loop.

Leave a Comment