我正在尝试使用函数为数字gusser编写代码: playOneGame函数的返回类型应为void。它应该在1到100的范围内实现一个完整的猜谜游戏 shouldPlayAgain函数应该有一个布尔返回类型。它应该提示用户确定用户是否想要再次播放,读入一个字符,如果该字符是'y'则返回true,否则返回false。 此外,您应该实现辅助函数getUserResponseToGuess和getMidpoint。应该在playOneGame函数中调用它们。 getUserResponseToGuess。此功能应该提示用户使用短语“是吗? (h / l / c):“替换令牌的值。它应该返回一个char。 char应该是三个可能值之一:'h','l'或'c'。它应该有以下签名: char getUserResponseToGuess(int guess) getMidpoint。这个函数应该接受两个整数,它应该返回两个整数的中点。如果在范围的中间有两个值,那么您应该始终选择两者中较小的一个。它应该有以下签名: int getMidpoint(int low,int high) 我从头开始,但我仍然无法得到它的逻辑。这就是我到目前为止所做的。
#include<iostream>
using namespace std;
void playOneGame;
char getUserResponseToGuess(int guess);
int getMidpoint ( int low, int high);
int main() {
do
{
playOneGame();
} while (shouldPlayAgain());
return 0;
}
void playOneGame
{
int a = 100;
cout << "\nGuess a number between 1 and 100. " <<endl;
getUserResponseToGuess ( a);
}
char getUserResponseToGuess(int guess)
{
while (true)
{
int guess = getMidpoint(minimum, maximum);
std::cout << "\nIs it [h]igher/[l]ower/[e]qual to " << guess << "? ";
char answer;
if (!(std::cin >> answer))
{
std::cerr << "error reading user input, program exiting\n";
exit(1);
}
if (answer == 'h')
minimum = guess + 1;
else if (answer == 'l')
maximum = guess - 1;
else if (answer == 'e')
{
std::cout << "Well, isn't that nice.\n";
return;
}
if (minimum > maximum)
{
std::cerr << "hey, you lied to me!\n";
exit(1);
}
}
}
int getMidpoint ( int low, int high)
{
int mid;
mid = (low + high) / 2;
return mid;
}
答案 0 :(得分:1)
猜测循环应该像这样循环:
while (true)
{
int guess = getMidpoint(minimum, maximum);
std::cout << "\nIs it [h]igher/[l]ower/[e]qual to " << guess << "? ";
char answer;
if (!(std::cin >> answer))
{
std::cerr << "error reading user input, program exiting\n";
exit(1);
}
if (answer == 'h')
minimum = guess + 1;
else if (answer == 'l')
maximum = guess - 1;
else if (answer == 'e')
{
std::cout << "Well, isn't that nice.\n";
return;
}
if (minimum > maximum)
{
std::cerr << "hey, you lied to me!\n";
exit(1);
}
}