Home >Backend Development >C++ >How Can I Generate Unique Random Numbers in a C Loop?
Generating Unique Random Numbers in a Loop in C
In C , the rand() function is commonly used to generate random numbers. However, when used within a loop, it may produce the same random values each iteration. This issue arises due to the inherent nature of the pseudorandom number generator used by rand().
To generate truly unique random numbers within a loop, it is crucial to call the srand() function before the loop initialization:
int main() { srand(time(NULL)); // Initialize random number generator only once, outside the loop for (int t = 0; t < 10; t++) { int random_x = rand() % 100; // Generate a random number cout << "\nRandom X = " << random_x; } return 0; }
The above is the detailed content of How Can I Generate Unique Random Numbers in a C Loop?. For more information, please follow other related articles on the PHP Chinese website!