繁体   English   中英

逻辑与或运算符和一个简单的 C++ 问题

[英]Logical AND OR Operators and a simple C++ problem

我正在处理我的工作簿中的 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;
}

代码按其编写方式工作。 嗯,差不多。 我需要用户输入来满足某些条件。 如果用户使用红色、蓝色或黄色以外的任何颜色,我需要程序显示错误消息。 它不会按照它的编写方式这样做。 但是按照原来的写法,它只会给我一个错误信息,即使我会输入必要的颜色。 例如:

if ((input1 != "red" || input1 != "blue" || input1 != "yellow")&&(input2 != "red" || 
input2 != "blue" || input2 != "yellow"))

我试图用伪代码对此进行推理,看看它是否有意义,而且看起来确实如此。 这是我的推理:如果 input1 不等于 red、blue 或 yellow,并且 input2 不等于 red、blue 或 yellow,则返回错误代码。

我似乎无法弄清楚我做错了什么。 有人可以帮我完成这个吗?

input1 = "red" || input1 = "blue" input1 = "red" || input1 = "blue"总是为真,试着考虑一个输入,它会返回假。 它必须等于redblue ,这是不可能的。

如果你想要“如果输入不是任何选项”,你想要input1 = "red" && input1 = "blue" 我认为您首先需要以下if

if((input1 != "red" && input1 != "blue" && input1 != "yellow") 
   || (input2 != "red" && input2 != "blue" && input2 != "yellow"))

意思是,“如果input1不是这三个选项中的任何一个,或者input2不是其他三个选项中的任何一个,则输入不正确。”

一般来说,将这些子表达式放入临时变量中,并学习使用调试器来调试代码。

Quimby 正在通过他对您的具体问题的回答引导您朝着正确的方向前进。 我想提出另一个问题并提出建议:

如果我输入“red”然后输入“blue”,您的程序将打印“purple”。 但是如果我输入“blue”然后输入“red”(相反的顺序),你的程序将不会像我期望的那样打印“purple”。

同样,如果输入“red”然后输入“red”,我希望你的程序打印“the color these make is red.”。 你的程序也不会那样做。

有一个简单的解决方法是使用选择的 colors 的布尔值:

cin >> input1;
cin >> input2;

bool hasRed = (input1 == "red") || (input2 == "red");
bool hasBlue = (input1 == "blue") || (input2 == "blue");
bool hasYellow = (input1 == "yellow") || (input2 == "yellow");

bool isPurple = hasRed && hasGreen;
bool isOrange = hasRed && hasYellow;
bool isGreen = hasBlue && hasYellow;
bool isRed = hasRed && !hasYellow && !hasBlue;
bool isBlue = hasBlue && !hasYellow && !hasRed;
bool isYellow = hasYellow && !hasRed && !hasBlue;

那么你的打印语句是相似的:

if (isPurple) {
   cout << "You've got purple" << endl;
}
else if (isOrange) {
   cout << "You've got orange" << endl;
}
etc...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM