Home > Backend Development > C++ > body text

Why are My Random Numbers the Same Within Loop Iterations?

Mary-Kate Olsen
Release: 2024-11-04 10:02:01
Original
590 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!