Random number generator - why seed every time

前端 未结 7 2009
轻奢々
轻奢々 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 <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
            printf("%d", rand()%6 + 1);
    }  
    

    With seed:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
            srand(time(NULL));
            printf("%d", rand()%6 + 1);
    }
    
    0 讨论(0)
提交回复
热议问题