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

前端 未结 12 2402
忘了有多久
忘了有多久 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:43

    To quote from man rand :

    The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

    If no seed value is provided, the rand() function is automatically seeded with a value of 1.

    So, with no seed value, rand() assumes the seed as 1 (every time in your case) and with the same seed value, rand() will produce the same sequence of numbers.

提交回复
热议问题