2013-03-28 30 views
0

我無法弄清楚爲什麼我的程序在每一輪持續生成相同的隨機數字。事實上,除非我退出並重新啓動程序,否則這個號碼不會改變。由於我是C++新手,這應該是一個我不知道的相當微不足道的錯誤。以下是我的代碼,並提前感謝您的幫助。C++ rand()總是返回相同的數字

#include <iostream> 
#include <ctime> 
#include <cstdlib> 
#include <string> 
using namespace std; 

int getRandNum(); 

int main() 
{ 
    int randNum = getRandNum(); 

    srand((unsigned int) time(NULL)); 

. 
. 
. 

} 

int getRandNum() 
{ 
    int randNum; 

    randNum = rand() % 3 + 1; 

    return randNum; 
} 
+2

這是一個相當冗長的代碼片段,有很多不相關的東西。您應該嘗試將其縮減爲一個仍能證明問題的最小示例。所有實際的遊戲邏輯都與問題無關。無論如何,在這個過程中你可能會發現自己的問題。 – BoBTFish 2013-03-28 08:47:55

回答

2

只有一次,並使用這個結果對於所有的後續操作這也意味着第一次調用之前調用srand

另外,呼叫與srand播種隨機數發生器之後進行,像被正確地@ZdeslavVojkovic

+0

我明白了。謝謝。這是一個愚蠢的錯誤。 – user2218567 2013-03-28 09:02:03

2

您從功能getComputerChoice()呼叫rand。 但是,在您使用srand設置種子之前調用該函數。

你需要rand功能,你打電話你computerChoice函數之前getComputerChoice

+0

只是注意到這並不能真正解決問題(請參閱icepack的回答),但順序應該仍然會改變。 – Dukeling 2013-03-28 08:49:20

0

提到你需要移動int computerChoice = getComputerChoice();do循環內。上面的代碼在開始時選擇一個選項,然後從不選擇另一個。

0

您只需在getPlayerChoice()下方編寫getComputerChoice(),即可解決問題。

playerChoice = getPlayerChoice(); 
computerChoice = getComputerChoice(); 
0

問題在你的算法,你叫getComputerChoice()只有一次在主()的開頭,但你需要做在你做...而:

... 
if(playQuitOption == 'p' || playQuitOption == 'P') 
    { 
     cout << endl; 

     playerChoice = getPlayerChoice(); 
     computerChoice = getComputerChoice(); 
...