Home >Backend Development >C++ >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:
srand(time(NULL)); // Initialize RNG outside of loop
random_x = rand() % 100;
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!