2017-10-29 60 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; 
}