Call srand inside a while loop always creates the same numbers with rand()

Viewed 35

I am in my first week of self taught cpp, sorry if this is basic. My mother works in a hospital and is required to inspect a random 20% of the daily admissions. She has found that she is repeating patterns unintentionally and would like to find a way to randomly choose the inspections. I had just created a random number generator the night before and thought that it could be done with a while statement. Instead of getting all random numbers, it repeats the same number the correct number of times. I don't have a good understanding of seeding, but my thought is that I am seeding it with time and since it is repeating rapidly it is re-running too quickly to generate a different number. It doesn't bother me if you just send me to a source for a better understanding of what I'm doing! Thanks in advance.

Here's the code.

    //Program to generate random numbers as a % of total admissions
    // My first real world project

    #include <iostream>
    #include <cstdlib>
    #include <ctime>

    int count = 0;
    int admissions = 2;

    int main()
    {
        std::cout << "How many admissions today? ";
        std::cin >> admissions;
        int cycles = admissions * .2;

        while (true)
        {
            if (count == cycles)
            {
                break;
            }
            srand(static_cast<unsigned int>(time(0)));
            int random_number = rand();
            std::cout << "\nYour numbers are: " << random_number % cycles+1;
            count += 1;
        }

        return 0;

    }
0 Answers
Related