2016-11-04 148 views
-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; 
} 

很抱歉,如果我弄错的东西,感谢帮助

+1

您不断重置种子。 –

+2

尽量不要在每个函数调用中改变种子。尝试调用这个'srand(time(0));'一次只在main(或其他地方)。 – jamesjaya

+0

工作,感谢很多家伙 –

回答

0

srand功能种子的随机数发生器。对于给定的种子值,生成相同的一组随机数。

由于您每次需要一个随机数时重新播种,使用当前时间作为种子,假设每次调用该函数都发生在同一秒内,随机数函数会播种相同的值,因此您应该保留获得相同的“随机”数字。

您应该在程序开始时只拨打srand一次。从dorand中删除呼叫,并将其置于main的顶部。