Random number generator - why seed every time

前端 未结 7 2042
轻奢々
轻奢々 2020-12-06 04:58

I am relative new to c and c++. In java, the language I am used to program in, its very easy to implement random number generation. Just call the the static random-method fr

7条回答
  •  不思量自难忘°
    2020-12-06 05:57

    The seed is needed for pseudo random number generator to generate different random number sequence from previous ones (not always). If you do not want the repeated sequence then you need to seed the pseudo random number generator.

    Try these codes and see the difference.
    Without seed:

    #include 
    #include 
    
    int main()
    {
            printf("%d", rand()%6 + 1);
    }  
    

    With seed:

    #include 
    #include 
    #include 
    
    int main()
    {
            srand(time(NULL));
            printf("%d", rand()%6 + 1);
    }
    

提交回复
热议问题