【发布时间】:2019-02-13 11:03:59
【问题描述】:
我正在做一个猜数字游戏。问题是:当数字被猜对并且计算机询问用户是否想再次玩时,它会接受输入并在退出游戏或重新启动之前再次询问相同的问题。
我尝试通过添加来调整 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)
【问题讨论】:
-
因为您在键入“C”时显式调用它。删除该呼叫。
标签: c++