2017-04-14 55 views
-1

我不明白为什么我一直得到相同的随机数 播放器和电脑。我滚了两次,一次为玩家,然后为计算机,我通过一个叫做roll_a_dice的函数来做。为什么我一直得到玩家和电脑的相同随机数?

PLZ忽略其他变量,他们是 与我的问题无关。

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




int roll_a_dice (void); 

int main(int argc, const char * argv[]) { 

int round=1, playerScore, playerTotal, computerScore, computerTotal; 
int player, computer; 


do{ 
    printf("Welcome to the Yacht game.\nLets see who is lucky!\n"); 

    player=roll_a_dice(); 
    computer=roll_a_dice(); 
    printf("Player: %d – Machine: %d\n",player, computer); 

}while (player!=computer||computer!=player); 



while(round!=12){ 



round++; 

} 

return 0; 
} 
int roll_a_dice (void){ 


srand(time(NULL)); 

return 1 + rand() % 6; 


} 
+2

只调用'srand()'一次来播种随机数发生器。通常这是在'main()'开始时完成的。 –

+0

与问题无关,但为什么你两次测试相同的条件'player!= computer || computer!= player'?这没有意义。删除其中之一 –

+0

谢谢它的工作! –

回答

2

rand()一般采用随机数生成器......这不是真正随机的,它只是给号码看似随机序列(在一系列的调用)。 srand()“种子”它,基本上确定序列开始的地方。所以如果你使用相同的种子,你会得到相同的序列。

由于您将roll_a_dice()两次靠近在一起,time(NULL)通常会给两次调用的结果相同(因为它们可能在同一秒内),所以您每次都使用相同的值再次获得相同的数字(首先按该顺序)。

您只需要在第一次拨打rand()之前拨种一次。根据您传递的种子值,再次调用srand()不必要地重新开始数字序列。

相关问题