Home >Backend Development >C++ >Why are My Random Numbers the Same Within Loop Iterations?

Why are My Random Numbers the Same Within Loop Iterations?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 10:02:01663browse

Why are My Random Numbers the Same Within Loop Iterations?

Same Random Numbers within Loop Iterations

In your loop that executes 15 times, you have invoked dh.setDoors() in each iteration. Inside this function, srand(time(0)) is called to initiate the generation of pseudo-random numbers. However, subsequent calls to rand() within the loop result in constant values of carSetter and decider throughout all 15 iterations.

This behavior occurs because srand(time(0)) sets the seed for the random number generator based on the current time. Since the loop executes quickly, time(0) returns the same value every time, resulting in the same sequence of pseudo-random numbers.

To overcome this issue, it is recommended to only call srand(time(0)) once at the start of the program, typically following a process such as:

<code class="c++">srand(time(0));

for (int i = 0; i < 15; i++) {
    carSetter = rand() % 3 + 1;
    decider = rand() % 2 + 1;
}</code>

By performing this initialization only once, the pseudo-random number generator will generate a unique sequence of numbers for each iteration of the loop, yielding the expected variation in the values of carSetter and decider.

The above is the detailed content of Why are My Random Numbers the Same Within Loop Iterations?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn