Home >Backend Development >C++ >How Can I Generate Unique Random Numbers in a C Loop?

How Can I Generate Unique Random Numbers in a C Loop?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 03:23:11185browse

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!

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