我想知道为什么 while (selection != 'q' && selection != 'Q') 有效但 while (selection != 'q' || selection != 'Q') 不起作用。它永远不会终止循环。当我使用 else if (selection == 'q' || selection == 'Q' ) (使用 || )时,它工作正常。有人可以帮忙吗?

#include <iostream>

using namespace std;

int main()
{
    char selection{};
    do{
        cout << "\n--------------------------"<< endl;
        cout << "1.Do this" << endl;
        cout << "2.Do that" << endl;
        cout << "3.Do something else" << endl;
        cout << "4.Quit" << endl;
        cout << "\nEnter your selection" << endl;
        cin >> selection;

        if (selection == '1')
            cout << "You chose 1 - doing this" << endl;
        else if (selection == '2')
            cout << "You chose 2 - doing that" << endl;
        else if (selection == '3')
            cout << "You chose 3 - doing  something else" << endl;
        else if (selection == 'q' || selection == 'Q' )
            cout << "Goodbye" << endl;
        else
            cout << "Unknown option -- try again" << endl;
    }
    while (selection != 'q' && selection != 'Q');
}

最佳答案

让我们看看您提出的条件,您想知道为什么它不起作用:

while (selection != 'q' || selection != 'Q')

为了使这个 while 循环终止循环,上述表达式的计算结果必须为 false。这就是 while 循环的工作原理。换句话说:
!(selection != 'q' || selection != 'Q')

必须是真的。 bool 逻辑的基本规则表明,这个表达式在逻辑上等价于
selection == 'q' && selection == 'Q'

这显然永远不会发生。 selection 值永远不能同时是 qQ。只有 Schrödinger's cat 可以做到这一点。

关于c++ do while 条件未按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62226151/

10-14 07:01