Why do I always get the same sequence of random numbers with rand()?

前端 未结 12 2392
忘了有多久
忘了有多久 2020-11-21 06:06

This is the first time I\'m trying random numbers with C (I miss C#). Here is my code:

int i, j = 0;
for(i = 0; i <= 10; i++) {
    j = rand();
    printf         


        
12条回答
  •  野的像风
    2020-11-21 06:42

    Rand does not get you a random number. It gives you the next number in a sequence generated by a pseudorandom number generator. To get a different sequence every time you start your program, you have to seed the algorithm by calling srand.

    A (very bad) way to do it is by passing it the current time:

    #include 
    #include 
    #include 
    
    int main() {
        srand(time(NULL));
        int i, j = 0;
        for(i = 0; i <= 10; i++) {
            j = rand();
            printf("j = %d\n", j);
        }
        return 0;
    }
    

    Why this is a bad way? Because a pseudorandom number generator is as good as its seed, and the seed must be unpredictable. That is why you may need a better source of entropy, like reading from /dev/urandom.

提交回复
热议问题