【发布时间】:2016-11-04 00:29:34
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int dorand(){
int i;
srand(time(0));
i = rand()%3+1;
return i;
}
int main (){
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
return 0;
}
问题是:四个 printf 正在打印相同的数字。 当我直接在主函数中执行 rand() 时,根本没有问题,但是当我调用一个函数时,随机生成会沉迷于相同的数字。有人有经验分享一下吗?
我试过了:
int main (){
srand(time(0)) //seeding in the main function before calling the dorand function
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
return 0;
}
还有
int dorand(){
int i;
i = 0; //clearing the variable before attributing a new rand value
srand(time(0));
i = rand()%3+1;
return i;
}
对不起,如果我弄错了什么,感谢您的帮助
【问题讨论】:
-
你一直在重置种子。
-
尽量不要每次函数调用都改变种子。尝试仅在 main(或其他地方)调用此
srand(time(0));一次。 -
工作,非常感谢大家
-
很高兴我们能提供帮助。如果您觉得有用,请随时 accept an answer。