rand() returns the same number each time the program is run

后端 未结 6 1679
自闭症患者
自闭症患者 2021-02-02 10:46

In this rather basic C++ code snippet involving random number generation:

include 
using namespace std;

int main() {
    cout << (rand() %         


        
6条回答
  •  礼貌的吻别
    2021-02-02 11:31

    srand() seeds the random number generator. Without a seed, the generator is unable to generate the numbers you are looking for. As long as one's need for random numbers is not security-critical (e.g. any sort of cryptography), common practice is to use the system time as a seed by using the time() function from the library as such: srand(time(0)). This will seed the random number generator with the system time expressed as a Unix timestamp (i.e. the number of seconds since the date 1/1/1970). You can then use rand() to generate a pseudo-random number.

    Here is a quote from a duplicate question:

    The reason is that a random number generated from the rand() function isn't actually random. It simply is a transformation. Wikipedia gives a better explanation of the meaning of pseudorandom number generator: deterministic random bit generator. Every time you call rand() it takes the seed and/or the last random number(s) generated (the C standard doesn't specify the algorithm used, though C++11 has facilities for specifying some popular algorithms), runs a mathematical operation on those numbers, and returns the result. So if the seed state is the same each time (as it is if you don't call srand with a truly random number), then you will always get the same 'random' numbers out.

    If you want to know more, you can read the following:

    http://www.dreamincode.net/forums/topic/24225-random-number-generation-102/

    http://www.dreamincode.net/forums/topic/29294-making-pseudo-random-number-generators-more-random/

提交回复
热议问题