Home >Backend Development >C++ >How to Avoid Repeating Random Numbers in a C Loop?

How to Avoid Repeating Random Numbers in a C Loop?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-21 06:49:10948browse

How to Avoid Repeating Random Numbers in a C   Loop?

How to Generate Truly Unique Random Numbers in a C Loop

In this code, you attempt to generate a different random number with each loop iteration:

for (int t = 0; t<10; t++)
{
    int random_x;
    srand(time(NULL));
    random_x = rand() % 100;
    cout << "\nRandom X = " << random_x;
}

However, the issue is that you're calling srand() multiple times inside the loop. This initializes the random number generator (RNG) each time with the same seed value, resulting in the same sequence of random numbers.

To generate truly unique random numbers in a loop, you need to follow these steps:

  1. Initialize the RNG once, outside of the loop. This ensures that a new seed value is used each time you execute the loop.
srand(time(NULL)); // Initialize RNG outside of loop
  1. Move the random number generation inside the loop. Replace the srand() call with rand(). This will generate a new random number for each iteration.
random_x = rand() % 100;
  1. Regarding resetting the RNG, calling srand() with a new seed value will reset the RNG initialization. You can do this inside the loop or at any point in your program where you need to reset the RNG.

By following these steps, you can generate different random numbers in each iteration of your loop.

The above is the detailed content of How to Avoid Repeating Random Numbers in a C Loop?. 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