-1
#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()时,根本没有任何问题,但是当我调用一个函数时,随机生成会沉迷于相同的数字。请有人分享一些经验吗?rand()数字在C中功能上瘾
我已经试过:
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;
}
很抱歉,如果我弄错的东西,感谢帮助
您不断重置种子。 –
尽量不要在每个函数调用中改变种子。尝试调用这个'srand(time(0));'一次只在main(或其他地方)。 – jamesjaya
工作,感谢很多家伙 –