“if”条件总是评估为“true”

时间:2017-09-15 05:59:45

标签: c++ if-statement

我正在使用字符串运行一系列if / else if / else语句,无论用户输入如何,if始终返回true:

cout << "Enter the element to look up: ";
cin >> elementLookup;
cout << endl << endl;

if (elementLookup == "H" || "Hydrogen" || "hydrogen") {
    cout << "Atomic Number: " << H_NUMBER << endl << endl;
    cout << "Atomic Mass: " << H_MASS << endl << endl;
}
else if (elementLookup == "He" || "Helium" || "helium") {
    cout << "Atomic Number: " << HE_NUMBER << endl << endl;
    cout << "Atomic Mass: " << HE_MASS << endl << endl;
}
else if (elementLookup == "Li" || "Lithium" || "lithium") {
    cout << "Atomic Number: " << LI_NUMBER << endl << endl;
    cout << "Atomic Mass: " << LI_MASS << endl << endl;
}

所有变量都已在代码中声明。出于某种原因,每次运行此代码时,无论用户输入如何,它都会说第一个if语句为true。我做错了什么“

4 个答案:

答案 0 :(得分:3)

if (elementLookup == "H" || "Hydrogen" || "hydrogen")

这是三个测试,或者一起进行。

第一个测试elementLookup == "H"测试字符串elementLookup是否与"H"相等。

其他两个测试测试字符串文字("Hydrogen" / "hydrogen")是否为非空。

总是如此。

您想要的是:

if (elementLookup == "H" || elementLookup == "Hydrogen" || elementLookup == "hydrogen")

答案 1 :(得分:0)

您必须更改if条件

    if (elementLookup == "H" || elementLookup == "Hydrogen" || elementLookup == "hydrogen") {

        cout << "Atomic Number: " << H_NUMBER << endl << endl;
        cout << "Atomic Mass: " << H_MASS << endl << endl;

    }
    else if (elementLookup == "He" || elementLookup == "Helium" || elementLookup == "helium") {
        cout << "Atomic Number: " << HE_NUMBER << endl << endl;
        cout << "Atomic Mass: " << HE_MASS << endl << endl;
    }

    else if (elementLookup == "Li" || elementLookup == "Lithium" || elementLookup == "lithium") {
        cout << "Atomic Number: " << LI_NUMBER << endl << endl;
        cout << "Atomic Mass: " << LI_MASS << endl << endl;
    }

对于每种情况,都必须进行检查。

if (elementLookup == "H" || "Hydrogen" || "hydrogen") 

这意味着首先进行相等的条件检查。之后&#34;氢/氢&#34;不是一个条件检查它总是变成一个合乎逻辑的&#34; 1&#34; / true。因为它有一些价值。所以最后|| ORed将永远是

答案 2 :(得分:0)

似乎与语法混淆。要检查elementLookup的值,语句应为:

    if (elementLookup == "H" || elementLookup == "Hydrogen" || elementLookup == "hydrogen") {
    //Rest of your code

让我们举一个例子来理解为什么如果条件总是计算为真:只有当变量为0或NULL时,语句 if(variable)才会计算为false。由于你的if语句中还有其他字符串,因此ORing它们总是计算为1.因此它始终为真。

答案 3 :(得分:-1)

这是因为OR条件而发生的。 “氢”是非空的,因此OR条件将始终为真,因此每次执行IF时都会执行。

相关问题