为什么C rand()函数每次都返回相同的序列?

时间:2020-04-09 16:59:41

标签: c random math.h

我最近编写了一个小程序来测试<math.h>中的C rand函数。

我已经编译了两次,并多次运行。在每次运行中,都输出相同的输出:

2
2
6
3
5
3

有人可以指出问题吗?

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int pick(int start, int end){
    int num  = ( rand()%end ) + start;
    return num;
}

int main(){

    int i;
    for(i=0; i<6; i++){
        printf("%d\n", pick(1, 6));
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

man page of rand():

srand()函数将其参数设置为rand()返回的新的伪随机整数序列的种子。 通过调用具有相同种子值的srand()可以重复这些序列。

如果未提供种子值,则将自动以1值播种rand()函数。

相关问题