Home > Article > Backend Development > Why Are My Random Numbers Always the Same in Each Loop Iteration?
Ensuring Different Random Numbers in Each Loop Iteration
In your code, you have a for loop that iterates 15 times, calling dh.setDoors() in each iteration. dh.setDoors() calls srand(time(0)), which sets the seed for the random number generator. Subsequently, whenever a random number is needed, it is generated using carSetter = rand()%3 1 or decider = rand()%2 1.
However, you have observed that the values of carSetter and decider remain the same throughout the 15 iterations. This occurs because calling srand(time(0)) at the beginning of each iteration sets the seed to the same value, which results in the same sequence of random numbers being generated.
The intended behavior is for carSetter and decider to generate different random numbers in each iteration. This is achievable by moving the call to srand(time(0)) outside of the loop, as follows:
srand(time(0)); for (int i = 0; i < 15; i++) { dh.setDoors(); }
This ensures that srand(time(0)) is called only once, at the start of the program, and thus a new random number sequence is generated before each iteration of the loop. This addresses the issue of the same pseudo-random numbers being generated in each loop.
The above is the detailed content of Why Are My Random Numbers Always the Same in Each Loop Iteration?. For more information, please follow other related articles on the PHP Chinese website!