我认为需要工作的区域是do while循环,因为我希望它只在捆绑时循环。但是,当用户赢或输时,它也会循环。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int ROCK = 1;
const int PAPER = 2;
const int SCISSORS = 3;
int getComputerChoice();
int getUserChoice();
void displayChoice(int);
int winner(int, int);
主要功能int main()
{
int computerChoice,
userChoice;
int playAgain;
DO WHILE循环确实有效,但是如果我赢了或者输了,它仍然会循环。我只想让它在发生领带时循环。
do
{
computerChoice = getComputerChoice();
userChoice = getUserChoice();
displayChoice(computerChoice);
playAgain = winner(computerChoice, userChoice);
} while (playAgain == 1);
return (0);
}
这得到计算机选择
int getComputerChoice()
{
unsigned seed = time(0);
srand(seed);
return (rand() % (SCISSORS - ROCK + 1)) + ROCK;
}
我认为这很好
int getUserChoice()
{
int uChoice;
cout << "Enter your choice of Rock, Paper, Scissors.n"
<< "(1) For rock, (2) for paper, (3) for scissors: ";
cin >> uChoice;
while (uChoice < 1 || uChoice > 3)
{
cout << "Please enter a number between 1 and 3. Try again, thank you.";
uChoice = getUserChoice();
}
return uChoice;
}
我认为这很好。
void displayChoice(int computerChoice)
{
cout << "Computer Choice: ";
if (computerChoice == 1)
cout << ROCK;
else if (computerChoice == 2)
cout << PAPER;
else if (computerChoice == 3)
cout << SCISSORS;
cout << endl;
}
我认为这个领域需要改进。
int winner(int computerChoice, int userChoice)
{
int playAgain = 1;
if (computerChoice == ROCK)
{
if (userChoice == SCISSORS)
{
cout << " You lose :( (The Rock smashes the Scissors) ";
}
else if (userChoice == PAPER)
{
cout << "You win! (Paper beats rock) ";
}
else if (userChoice == ROCK)
{
cout << "Its a tie. Play again.";
playAgain == 1;
}
}
else if (computerChoice == PAPER)
{
if (userChoice == ROCK)
{
cout << "You lose :( (Paper wraps rock)";
}
else if (userChoice == SCISSORS)
{
cout << "You win! (Scissors cuts paper)";
}
else if (userChoice == PAPER)
{
cout << "Its a tie. Play again.";
playAgain == 1;
}
}
else if (computerChoice == SCISSORS)
{
if (userChoice == ROCK)
{
cout << "You Win! (The rock smashes the scissors.)";
}
else if (userChoice == PAPER)
{
cout << "You lose :(. (Scissors cuts paper.)";
}
else if (userChoice == SCISSORS)
{
cout << "Its a tie. Play again.";
playAgain == 1;
}
}
cout << endl;
return playAgain;
}
winner
之内,您尝试更新playAgain
playAgain == 0
。但是==
是相等运算符. 它不执行赋值。赋值操作符是=
,即单个等号。因此,playAgain
永远不会更新,而winner()
总是返回1。
在更新变量值时,使用赋值操作符而不是相等操作符来修复。