Why do I get the same result with rand() every time I compile and run?

后端 未结 4 736
陌清茗
陌清茗 2020-11-27 07:47

Whenever I run this code, I get a same result.

Program

#include

int main(int agrc, const char *argv[]) {
 int i = rand();
 printf(\"         


        
4条回答
  •  一整个雨季
    2020-11-27 08:19

    You want to initialize the PRNG.

    Initialize it once (typically inside main()) with a call to the srand() function.

    If you do not initialize the PRNG, the default is to have it initialized with the value 1. Of course initializing it with some other constant value will not give you different pseudo random numbers for different runs of the program.

    srand(1); /* same as default */
    srand(42); /* no gain, compared to the line above */
    

    You need to initialize with a value that changes with each run of the program. The value returned from the time() function is the value most often used.

    srand(time(NULL)); /* different pseudo random numbers almost every run */
    

    The problem with time(NULL) is that it returns the same value at the same second. So, if you call your program twice at 11:35:17 of the same day you will get the same pseudo random numbers.

提交回复
热议问题