簡體   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