使用多个!=和||在if陈述中

时间:2019-11-12 04:30:10

标签: c++

我仍然是C ++的新手,当收到的输入(客户)不等于“ r”,“ R”,“ b”或“ B”时,我试图使代码打印为“无效的客户类型”。然后,它再次提示用户输入字母。使用我编写的代码“无效的客户类型”。即使客户==字母“ r”,“ R”,“ b”或“ B”之一时,仍会打印出。我尝试使客户成为char而不是string,但这并没有太大变化。

#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string customer;
    do
    {
        cout << "Pleas Enter the Customer Type (R for Regular, B for Business): " << endl;
        cin >> customer;
        if ((customer != "r") || (customer != "R") || (customer != "b") || (customer != "B"))
        {
            cout << "Invalid customer type." << endl;
        }

    } while ((customer != "r") || (customer != "R") || (customer != "b") || (customer != "B"));
    return 0;
}

2 个答案:

答案 0 :(得分:3)

使用&&代替||

#include <iostream>
#include <string>
using namespace std;

int main ()
{
    string customer;
    do
    {
        cout << "Pleas Enter the Customer Type (R for Regular, B for Business): " << endl;
        cin >> customer;
        if ((customer != "r") && (customer != "R") && (customer != "b") && (customer != "B"))
        {
            cout << "Invalid customer type." << endl;
        }

    } while ((customer != "r") && (customer != "R") && (customer != "b") && (customer != "B"));
    return 0;
}

为简单起见,如果我们仅采用前两个条件

(customer != "r") || (customer != "R")

这些条件之一将始终为true,并且在使用逻辑或时,如果任何子条件的值为true,则整个条件的值为true。

我们需要使用逻辑AND,以便如果任何子条件为假,则整个条件的值为假。

这有点令人困惑,因为如果您的条件是测试相等性而不是不平等,您将使用||

例如

if ((customer == "r") || (customer == "R") || (customer == "b") || (customer == "B"))

您还可以将代码重构得更多DRY

int main ()
{
    string customer;
    while(true)
    {
        cout << "Pleas Enter the Customer Type (R for Regular, B for Business): " << endl;
        cin >> customer;
        if ((customer == "r") || (customer == "R") || (customer == "b") || (customer == "B"))
        {
            break;
        }

        cout << "Invalid customer type." << endl;
    } 
}

答案 1 :(得分:2)

如果客户输入rRbB,则它是有效客户的输入。这意味着有效客户的条件将是:

((customer == "r") || (customer == "R") || (customer == "b") || (customer == "B"))

要检查客户的无效性,您必须采取上述条件的逻辑非

!((customer == "r") || (customer == "R") || (customer == "b") || (customer == "B"))

这将起作用。但是,您可以将De Morgan's Law应用于此表达式,结果将是:

((customer != "r") && (customer != "R") && (customer != "b") && (customer != "B"))