c++ - 如何使输出只打印一次

标签 c++

我正在制作一个数字猜谜游戏。问题是:当数字被正确猜中并且计算机询问用户是否想再次玩游戏时,它接收输入并在退出游戏或重新启动游戏之前再次询问相同的问题。

我尝试通过添加

来调整 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)

最佳答案

您应该从 playOneGame() 中删除对 shouldPlayAgain() 的调用。

它在每次从 playOneGame() 返回后在 main() 中调用。

关于c++ - 如何使输出只打印一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54661806/

相关文章:

c++ - 如何在wxWidgets中制作自定义边框而不破坏调整大小和移动?

c++ - 抛出一个 catch block (C++)是否有效?

c++ - APUE 第 7 章中的 hello world 以代码 0 退出

c++ - 数组是指针吗?

c++ - PJNATH 是否支持 ALTERNATE-SERVER 重定向?

c++ - 将接口(interface)和实现与普通功能分离

c++ - 从 class_Type 名称访问 vector 值不允许错误

c++ - static_assert 在 Visual C++ 10 中不起作用

c++ - 对象管理——容器还是工厂?

c++ - 将 ZMQ 上下文传递给线程