我正在做一个猜数字游戏。问题是:当正确猜出数字并且计算机询问用户是否要再次玩游戏时,它会接受输入并在退出游戏或重新启动游戏之前再次询问相同的问题。
我尝试通过添加
来调整shouldPlayAgain()函数else if(input == 'N')
return false;
但是我仍然遇到同样的问题。这是我的代码:*请注意,int main函数必须是这样的。我无法对其进行更改。
#include <iostream>
using namespace std;
//Function prototypes
void playOneGame();
char getUserResponseToGuess(int);
int getMidpoint(int, int);
bool shouldPlayAgain();
int main()
{
do
{
playOneGame();
} while (shouldPlayAgain());
return 0;
}
void playOneGame()
{
int low = 1;
int high = 100;
int guess = getMidpoint(low, high);
char response;
cout << "Welcome! Please think of a number from 1 to 100.\n";
response = getUserResponseToGuess(guess);
//Keeps guessing until it guesses the correct number
while(response != 'C')
{
if(response == 'H')
{
low = guess+1;
guess = getMidpoint(low, high);
response = getUserResponseToGuess(guess);
}
else if(response == 'L')
{
high = guess-1;
guess = getMidpoint(low, high);
response = getUserResponseToGuess(guess);
}
}
if(response == 'C')
{
shouldPlayAgain();
}
}
char getUserResponseToGuess(int guess)
{
char HLC;
cout << "Is the number " << guess << " ? (H/L/C)\n";
cin >> HLC;
return HLC;
}
int getMidpoint(int low, int high)
{
int mid = (low+high)/2;
return mid;
}
bool shouldPlayAgain()
{
char input;
cout << "Would you like to play again? (Y/N)\n";
cin >> input;
if(input == 'Y')
{
return true;
}
else return false;
}
这是示例输出。我不明白为什么在最终执行之前将问题打印两次。任何帮助表示赞赏。谢谢。
Welcome! Please think of a number from 1 to 100.
Is the number 50 ? (H/L/C)
L
Is the number 25 ? (H/L/C)
H
Is the number 37 ? (H/L/C)
H
Is the number 43 ? (H/L/C)
L
Is the number 40 ? (H/L/C)
C
Would you like to play again? (Y/N)
Y
Would you like to play again? (Y/N)
Y
Welcome! Please think of a number from 1 to 100.
Is the number 50 ? (H/L/C)
答案 0 :(得分:1)
您应该从shouldPlayAgain()
中删除对playOneGame()
的呼叫。
每次从main()
返回后,就会在playOneGame()
中调用它。