I have a for loop that runs 15 times, with dh.setDoors() in every iteration.
What setDoors does is call srand(time(0)), then whenever a random number is needed it’ll use, for example, carSetter = rand()%3+1. Alternatively, it may use decider = rand()%2+1.
Now, normally decider and carSetter are used in a different ways, but I suspected a problem and made it print out carSetter and decider at every iteration. Here’s what came out:
Door 1 has car
Decider is 2
Door 1 has car
Decider is 2
Door 1 has car
Decider is 2
Door 1 has car
Decider is 2
Door 1 has car
Decider is 2
etc...
The values ‘1’ and ‘2’ change when I run it multiple times, but are still the same throughout the 15 times.
Since the loop is running 15 different times, shouldn’t carSetter and decider print out a different random number every iteration?
When I don’t have srand(time(0)), it works as expected, but there’s no seed set, so it’s the same sequence of “random” numbers each time, so it’s probably a problem with the seed?
When you call
srand(x), then the value ofxdetermines the sequence of pseudo-random numbers returned in following calls torand(), depending entirely on the value ofx.When you’re in a loop and call
srand()at the top: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. Soxandywill be the same each iteration.Instead, you only usually need to call
srand()once at the start of your program:In the above case,
xandywill have different values each time through the loop.