c++ - 为什么我的 'while' 语句之一在我的另一个 'while' 语句为真时执行?

标签 c++ while-loop

注意:我使用的是C++

为什么我的一个“while”语句(“while”编号 1)仍然执行,而我放在其上方的另一个“while”语句(“while”编号 2)有效?这让我很困扰,因为虽然 'while' 数字 1 不是真的,但是 'while' 数字 2 是真的,但是 'while' 数字 1 仍然执行而不是 'while' 数字 2。任何人都可以帮助我,或解释这个吗?这是我的代码:

#include <iostream>
#include <string>

using namespace std;

void PancakeGlutton()
{
    int answer;
    cout << "Good morning!" << endl;
    cout << "Would you like to enter pancake data? Press 1 to accept, press 2 to decline: ";
    cin >> answer;

    while (answer == 1) {
        int totalPeople = 10;
        int totalPancakes = 0;
        int input;
        int lowest = 100000;
        int highest = 0;

        for (int i = 9; i >= 0; --i) {
            cout << "How many pancakes did you eat this morning? I will be asking this question " << i << " more times." << endl;
            cin >> input;

            totalPancakes += input;

            if (input >= highest) {
                highest = input;
            }

            if (input <= lowest) {
                lowest = input;
            }
        }

        double pancakeAverage = double(totalPancakes) / double(totalPeople);

        cout << "The total number of pancakes eaten was " << totalPancakes << " pancakes " << endl;
        cout << "The average number of pancakes eaten was " << pancakeAverage << " pancakes " << endl;
        cout << "The highest number of pancakes eaten was " << highest << " pancakes" << endl;
        cout << "The lowest number of pancakes eaten was " << lowest << " pancakes" << endl;
        cout << "" << endl;
        cout << "Do you want to enter more pancake data? Press 1 to accept, press 2 to decline: ";
        cin >> answer;
    }
    // while number 1:
    while (answer == 2) {
        break;
    }

    // while number 2:
    while (answer != 1 || answer != 2) {
        cout << "Error: please enter a valid answer. 1 or 2? ";
    cin >> answer;
    }
}

int main()
{
    PancakeGlutton();
    system("PAUSE");
    return EXIT_SUCCESS;
}

最佳答案

while (answer != 1 || answer != 2) {
        cout << "Error: please enter a valid answer. 1 or 2? ";
    cin >> answer;
}

必须是

while (answer != 1 && answer != 2) {
        cout << "Error: please enter a valid answer. 1 or 2? ";
    cin >> answer;
}

关于c++ - 为什么我的 'while' 语句之一在我的另一个 'while' 语句为真时执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32389534/

相关文章:

c - 我的 while 循环与 char 不起作用。请提供一些帮助

c++ - (C++) OOP - 用类扩展 - 初学者的困境

c++ - 可能的内存泄漏

c++ - Qt Creator Ubuntu版本奇怪的编译错误

C++ unique_ptr 从派生到基础的转换

java - 为什么不重新评估 while 条件?

PHP 代码不会在 while 循环中迭代到下一个数据变量(使用 bootstrap)

c - C 中的 while 循环条件错误的原型(prototype)函数

c++ - 展开多维数组指针失败c++

python - 是否可以在这段代码中使用 "while something"而不是 "while True"?