我正在处理我的工作簿中的一个 C++ 问题,并且我在这个问题(以及我遇到的许多其他问题)中的逻辑运算符的行为方面遇到了困难。
这是代码:
#include <iostream>
using namespace std;
int main()
{
string input1, input2;
cout << "Enter two primary colors to mix. I will tell you which secondary color they make." << endl;
cin >> input1;
cin >> input2;
if ((input1 != "red" && input1 != "blue" && input1 != "yellow")&&(input2 != "red" && input2 != "blue" && input2 != "yellow"))
{
cout << "Error...";
}
else
{
if (input1 == "red" && input2 == "blue")
{
cout << "the color these make is purple." << endl;
}
else if (input1 == "red" && input2 == "yellow")
{
cout << "the color these make is orange." << endl;
}
else if (input1 == "blue" && input2 == "yellow")
{
cout << "the color these make is green." << endl;
}
}
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码按照其编写方式正常工作。嗯,差不多了。我需要用户输入来满足某些条件。如果用户使用红色、蓝色或黄色以外的任何颜色,我需要程序显示错误消息。它不会按照它所写的方式这样做。但按照原来的编写方式,即使我输入了所需的颜色,它也只会给我一条错误消息。例如:
if ((input1 != "red" || input1 != "blue" || input1 != "yellow")&&(input2 != "red" ||
input2 != "blue" || input2 != "yellow"))
Run Code Online (Sandbox Code Playgroud)
我试图用伪代码来推理这一点,看看它是否有意义,而且看起来确实如此。这是我的推理:如果 input1 不等于红色、蓝色或黄色,并且 input2 不等于红色、蓝色或黄色,则返回错误代码。
我似乎无法弄清楚我做错了什么。有人可以引导我完成这个吗?
input1 != "red" || input1 != "blue"始终为 true,请尝试考虑将返回 false 的输入。它必须等于red和blue,这是不可能的。
如果您想要“如果输入不是任何选项”,那么您需要input1 != "red" && input1 != "blue". 我认为您首先需要以下内容if:
if((input1 != "red" && input1 != "blue" && input1 != "yellow")
|| (input2 != "red" && input2 != "blue" && input2 != "yellow"))
Run Code Online (Sandbox Code Playgroud)
意思是,“如果input1不是这三个选项中的任何一个或 input2不是其他三个选项中的任何一个,则输入不正确。”
一般来说,将这些子表达式放入临时变量中并学习使用调试器来调试代码。