2017-10-29 63 views
0

我目前正在研究Rock,Paper,Scissors程序。我們需要包含四個函數,getComputerChoice,getUserChoice,displayChoice和determineWinner。我目前被卡在displayChoice上,我想顯示用戶使用字符串選擇的「武器」,但它不起作用。任何幫助/反饋將不勝感激,謝謝。字符串不在功能內部打印

#include <iostream> 
#include <cstdlib> 
#include <time.h> 
#include <string> 
using namespace std; 


void getComputerChoice(int& computerChoice); 
int getUserChoice(int userChoice); 
void displayChoice(int userChoice, int computerChoice); 

int main() 
{ 
    int userChoice = 0, computerChoice; 

    getUserChoice(userChoice); 
    getComputerChoice(computerChoice); 
    displayChoice(userChoice, computerChoice); 


    return 0; 
} 

int getUserChoice(int userChoice) 
{ 
    cout << "Game Menu\n" 
    << "-----------\n" 
    << "1. Rock\n" 
    << "2. Paper\n" 
    << "3. Scissors\n" 
    << "4. Quit\n" 
    << "Enter your choice (1-4):"; 
    cin >> userChoice; 
    return (userChoice); 
} 

void getComputerChoice(int& computerChoice) 
{ 
    srand(time(NULL)); 
    computerChoice = (rand() % 3) + 1; 
} 

void displayChoice(int userChoice, int computerChoice) 
{ 
    string uChoice; 
    if (userChoice == 1) 
     uChoice = "Rock"; 
    else if (userChoice == 2) 
     uChoice = "Paper"; 
    else if (userChoice == 3) 
     uChoice = "Scissors"; 

    cout << "You selected :" << uChoice << endl; 
    cout << "The computer selected :" << computerChoice << endl; 
} 
+1

'userChoice'將始終爲0,您不會從'getUserChoice'中檢索值。 – George

+0

通過'userChoice = getUserChoice(userChoice)'來修復',不敢相信我錯過了。萬分感謝! – Ivan

+0

你也不需要參數'getUserChoice(int)',你只是覆蓋你的輸入,而且你也沒有通過引用傳遞。你可以使它成爲'userChoice = getUserChoice()',它將以同樣的方式工作。只要確保更新你的函數定義。 –

回答

0

你的問題的範圍,你就是簡單地返回您傳遞的功能,而不是什麼用戶提供輸入,您應該使用單獨的變量該變量的值。您的get函數不需要參數,getComputerChoice函數也應該是int類型的。這些更改應該會爲您提供正確的輸出:

#include <iostream> 
#include <cstdlib> 
#include <time.h> 
#include <string> 
using namespace std; 


int getComputerChoice(); 
int getUserChoice(); 
void displayChoice(int userChoice, int computerChoice); 

int main() 
{ 
int userChoice = 5; 
int computerChoice= 5; 

userChoice = getUserChoice(); 
computerChoice = getComputerChoice(); 
displayChoice(userChoice, computerChoice); 


return 0; 
} 

int getUserChoice() 
{ 
    int selection=5; 
    cout << "Game Menu\n" 
    << "-----------\n" 
    << "1. Rock\n" 
    << "2. Paper\n" 
    << "3. Scissors\n" 
    << "4. Quit\n" 
    << "Enter your choice (1-4):"; 
    cin >> selection; 
    return selection; 
} 

int getComputerChoice() 
{ 
    srand(time(NULL)); 
    return (rand() % 3) + 1; 
} 

void displayChoice(int userChoice, int computerChoice) 
{ 
    string uChoice; 
    if (userChoice == 1) 
     uChoice = "Rock"; 
    else if (userChoice == 2) 
     uChoice = "Paper"; 
    else if (userChoice == 3) 
     uChoice = "Scissors"; 

    cout << "You selected : " << uChoice << endl; 
    cout << "The computer selected : " << computerChoice << endl; 
}