【发布时间】:2021-11-19 14:59:56
【问题描述】:
我们应该使用函数编写一个石头、剪子布的游戏。除了确定获胜者并展示这一点之外,我已经完成了所有工作。 “无效结果”是我遇到的问题。
目前,我可以选择石头剪刀布,让电脑显示用户的选择和电脑的选择。这是我当前的代码:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int user(int);
int pc(int);
int result(int);
string userChoice, pcChoice;
int userNum, pcNum;
void result(int, int);
int main()
{
user(userNum);
pc(pcNum);
cout << "You chose " << userChoice << endl << "They chose " << pcChoice;
return 0;
void result();
}
int user(int userNum)
{
cout << "Choose rock, paper, or scissors: ";
cin >> userChoice;
if(userChoice == "rock")
{
userNum = 1;
}
else if(userChoice == "paper")
{
userNum = 2;
}
else if(userChoice == "scissors")
{
userNum = 3;
}
else
{
cout << "Input invalid. Run again and enter rock, paper, or scissors." << endl;
exit(0);
}
return userNum;
}
int pc(int pcNum)
{
srand(time(0));
pcNum = (rand() % 3 + 1);
if (pcNum == 1)
{
pcChoice = "rock";
}
else if (pcNum == 2)
{
pcChoice = "paper";
}
else if (pcNum == 3)
{
pcChoice = "scissors";
}
return pcNum;
}
void result(int pcNum, int userNum)
{
if (pcNum == 1)
{
if (userNum == 1)
{
cout << "Tie. Play again.";
}
else if (userNum == 2)
{
cout << "You win. Paper covers rock.";
}
else if (userNum == 3)
{
cout << "You lose. Rock breaks scissors.";
}
}
else if (pcNum == 2)
{
if (userNum == 1)
{
cout << "You lose. Paper covers rock.";
}
else if (userNum == 2)
{
cout << "Tie. Play again.";
}
else if (userNum == 3)
{
cout << "You win. Scissors cut paper.";
}
}
else if (pcNum == 3)
{
if (userNum == 1)
{
cout << "You win. Rock breaks scissors.";
}
else if (userNum == 2)
{
cout << "You lose. Scissors cut paper";
}
else if (userNum == 3)
{
cout << "Tie. Play again.";
}
}
}
【问题讨论】:
-
旁注:
pcNuminpc隐藏了全局pcNum并且您不使用返回值。user中的userNum相同。最好避免使用全局变量。
标签: c++