c++ - 为什么这个简单的逻辑不起作用?

标签 c++

我只是想不通为什么 while 循环中的这个简单逻辑不起作用。

基本上这个函数的作用是,它接受一个参数,并在 while 循环中检查它是否不是"is"或“否”,然后继续循环。

void getAnswer(string answer) {

    string newAnswer = "";
    newAnswer = answer;
    while (newAnswer != "Yes" || newAnswer != "yes" || newAnswer != "Y" || newAnswer != "y" || newAnswer != "No" || newAnswer != "no") {
            cout << "Enter yes or no.." << endl;
            cin >> newAnswer;

        }

        if (newAnswer == "Yes" || newAnswer == "yes" || newAnswer == "Y" || newAnswer == "y") {
            chooseOptions();
        } else {
            cout << "Bye See you again " << endl;
            exit(1);
        } 
}

但即使我输入“yes”或“no”,它仍然会循环。

最佳答案

De Morgan's laws声明:

"not (A and B)" is the same as "(not A) or (not B)"

根据您的情况应用此法律:

newAnswer != "Yes" || newAnswer != "yes" || ...

!(newAnswer == "Yes" && newAnswer == "yes" && ...)

现在更容易看出错误的原因。

如果 newAnswer 不是“Yes”或“yes”,它将被评估为 true,这不是您想要的。

解决方案是将 || 更改为 &&

关于c++ - 为什么这个简单的逻辑不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31020026/

相关文章:

C++ 子类模块化函数

c++ - 如何删除C++中给定矩阵中的特定行和列?

c++ - 我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?

c++ - OpenGl 纹理....... ppm 背景

c++ - 将值输入二维数组并打印

c++ - Doxygen 未记录的字符串值

c++ - 如何像在 Process Explorer 中那样获取进程起始地址的 "name"?

c++ - Visual Studio 自动构建 : Makefile vs Project. sln

c++ - 使用 C++ (Zune/ZDK) 在 WinCE 上构建 LPCWSTR

C++11 将枚举转换为整数