c ++ do while 条件未按预期工作

log*_*_92 3 c++

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

#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');
}
Run Code Online (Sandbox Code Playgroud)

Sam*_*hik 5

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

while (selection != 'q' || selection != 'Q')
Run Code Online (Sandbox Code Playgroud)

为了使该while循环终止循环,上述表达式的计算结果必须为假。这就是while循环的工作方式。换句话说:

!(selection != 'q' || selection != 'Q')
Run Code Online (Sandbox Code Playgroud)

必须是真的。布尔逻辑的基本规则表明,这个表达式在逻辑上等价于

selection == 'q' && selection == 'Q'
Run Code Online (Sandbox Code Playgroud)

这显然永远不会发生。该selection值不能q与Q在同一时间。只有薛定谔的猫才能做到这一点。