这是我的密码:
#include<stdio.h>
#include<stdlib.h>
#include <time.h>
int main(){
float m, n;
printf("Enter n, m:");
scanf("%f %f", &n, &m);
int l;
l=m-n;
int i;
for(i=0; i<4; i++){
srand(time(NULL));
double r=rand();
r/=RAND_MAX;
r*=l;
r+=n;
printf("%f ", r);
}
return 0;
}为什么它产生相同的数字?当我在循环之前写srand(time(NULL));时,它会生成不同的数字!为什么是这样?这个程序是如何工作的?
发布于 2015-10-21 03:35:44
对time(NULL)的调用返回当前日历时间(自1970年1月1日以来的秒数)。所以这就是你给的一样的种子。所以兰德给出了同样的价值。
您可以简单地使用:
srand (time(NULL)+i);发布于 2015-10-21 03:20:09
srand()是随机数序列的种子。
srand函数使用参数作为新的伪随机数序列的种子,这些伪随机数将在后续调用rand时返回。如果用相同的种子值调用srand,则将重复伪随机数的序列。C11dr§7.22.2.2 2
time()通常是相同的值-对于第二个@kaylum
编辑
最好在代码的早期只调用srand()一次
int main(void) {
srand((unsigned) time(NULL));
...或者,如果每次都想使用相同的序列,那么根本不要调用srand() --这对调试非常有用。
int main(void) {
// If code is not debugging, then seed the random number generator.
#ifdef NDEBUG
srand((unsigned) time(NULL));
#endif
...https://stackoverflow.com/questions/33250156
复制相似问题