Generating Distinct Random Numbers Within a Loop in C
In C , writing code to generate random numbers within a loop can sometimes yield unexpected results. Consider the following code snippet:
for (int t = 0; t < 10; t++) { int random_x; srand(time(NULL)); random_x = rand() % 100; cout << "\nRandom X = " << random_x; }
The issue with this code lies in the repeated use of srand(time(NULL)) within the loop. While srand() is used to initialize the random number generator, calling it multiple times during the iteration will result in the generation of the same sequence of random numbers.
To generate different random numbers in each iteration, srand() should be called only once, preferably at the beginning of the program. This ensures that the seed for the random number generator is set just once, effectively "randomizing" the starting point for each iteration.
int main() { srand(time(NULL)); for (int t = 0; t < 10; t++) { int random_x = rand() % 100; cout << "\nRandom X = " << random_x; } }
Moreover, if you need to reset the random number initialization completely, you can call srand() again with a different seed value. This will generate a new sequence of random numbers, distinct from the previous one.
The above is the detailed content of How to Generate Distinct Random Numbers in a C Loop?. For more information, please follow other related articles on the PHP Chinese website!