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

后端 未结 5 1140
生来不讨喜
生来不讨喜 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条回答
  • 2020-11-29 12:50

    It is common to seed the random number generator with the current time. Try:

    srand(time(NULL));

    0 讨论(0)
  • 2020-11-29 13:01

    I think that the point of these articles is to have a go at implementing the algorithm that is in rand() not how to seed it effectively.

    producing (pseudo) random numbers is non trivial and is worth investigating different techniques of generating them. I don't think that simply using rand() is what the authors had in mind.

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 2020-11-29 13:11

    Option 2 isn't difficult, here you go:

    srand(time(NULL));
    

    you'll need to include stdlib.h for srand() and time.h for time().

    0 讨论(0)
  • 2020-11-29 13:13

    The problem is that if you don't seed the generator it will seed itself with 0 (as if srand(0) were called). PRNGs are designed to generate the same sequence when seeded the same (due to the fact that PNRGs are not really random, they're deterministic algorithms and maybe a bit because it's quite useful for testing).

    When you're trying to seed it with a random number using

    srand(rand());
    

    you're in effect doing:

    srand(0);
    x = rand();   // x will always be the same.
    srand(x);
    

    As FigBug mentioned, using the time to seed the generator is commonly used.

    0 讨论(0)
提交回复
热议问题