What's the Right Way to use the rand() Function in C++?

后端 未结 5 1147
生来不讨喜
生来不讨喜 2020-11-29 12:16

I\'m doing a book exercise that says to write a program that generates psuedorandom numbers. I started off simple with.

#include \"std_lib_facilities.h\"

in         


        
5条回答
  •  猫巷女王i
    2020-11-29 13:08

    srand() should only be used once:

    int randint()
    {
        int random = rand();
        return random;
    }
    
    int main()
    {
        // To get a unique sequence the random number generator should only be
        // seeded once during the life of the application.
        // As long as you don't try and start the application mulitple times a second
        // you can use time() to get a ever changing seed point that only repeats every
        // 60 or so years (assuming 32 bit clock).
        srand(time(NULL));
        // Comment the above line out if you need to debug with deterministic behavior.
    
        char input = 0;
        cout << "Press any character and enter to generate a random number." << endl;
    
        while (cin >> input)
        {
            cout << randint() << endl;
        }
        keep_window_open();
    }
    

提交回复
热议问题