Generating Unique Random Numbers Within a Loop in C
While looping through a set of iterations, it can be desirable to generate different random numbers each time the loop executes. However, using the default random number generator in C (srand) within the loop can result in the same number being generated repeatedly.
Resetting Random Number Initialization
To avoid this issue and ensure the generation of unique random numbers, it is crucial to reset the seed of the random number generator using srand(). This function takes an integer as an argument, and when called, it initializes the internal state of the random number generator.
Implementation
Here's an example that showcases how to generate unique random numbers within a loop:
#include <iostream> #include <cstdlib> #include <ctime> int main() { srand(time(NULL)); // Initialize the random number generator once // Execute the loop 10 times and generate a different random number each time for (int t = 0; t < 10; t++) { int random_x = rand() % 100; std::cout << "\nRandom X = " << random_x << std::endl; } return 0; }
How it Works
In this example, we use the time(NULL) function to generate a seed based on the current time. This ensures that the seed will be different each time the program is run. By setting the seed with srand() once outside the loop, we guarantee that the random number generator will produce a unique stream of numbers.
Resetting Random Number Initialization
The srand() function also resets the random number generator to its initial state, discarding any previous seed. This means that subsequent calls to rand() will generate a new sequence of numbers based on the newly set seed.
The above is the detailed content of How to Generate Unique Random Numbers in a C Loop?. For more information, please follow other related articles on the PHP Chinese website!