“if”语句中带有“或”运算符不起作用

时间:2015-07-08 20:03:15

标签: c++

如果他们选择的数字不是1 2或3,请尝试让我的程序让用户输入输入。
 但是每当我输入1 2或3时,它仍然希望我重新输入一个整数。我使用我的或操作员错了吗?

#include <iostream>
#include <string> 

using namespace std; 

int main()
{

    cout << "Choose option 1,2 or 3: \n";
    cout << "1: Drop a single chip into one slot \n";
    cout << "2: Drop multiple chips into one slot \n";
    cout << "3: Quit the program \n";

    int choice;
    cin >> choice; 

    if  (choice != 1||2||3)
    {
        cout << "Please enter 1 2 or 3 \n";
        cin >> choice;
    }

        else 

            {
                cout << "it worked \n";
            }
}

4 个答案:

答案 0 :(得分:3)

因为你的if

choice != 1||2||3  

正在评估:

int != int|| true || true

这总是正确的(某些东西是或是或是 - >是)

每个归零到布尔值的非零整数(x!=0)值将变为true

因为人类和计算机无法对1号码做出决定 - 您必须将其更改为truefalse(是或否)

要解决此问题,只需将其更改为:

if (choice != 1 && choice != 2 && choice != 3)

编辑:感谢@StillLearning的改进

答案 1 :(得分:3)

if语句中的这个条件

if  (choice != 1||2||3)

相当于

if  ( ( choice != 1 ) || 2 || 3 )

所以它始终等于true,因为即使choice != 1评估为false,表达式23总是不等于零,因此每个他们评价为true

您的意思是以下

if  ( ( choice != 1 ) && ( choice != 2 ) && ( choice != 3 ) )

或者你可以写得更简单

if  ( choice < 1  || choice > 3 )

或者这个可能更具可读性

if  ( !( 1 <= choice && choice <= 3 ) )

甚至以下方式:)

if  ( not ( 1 <= choice && choice <= 3 ) )

考虑到你可以将这部分程序包含在do-while循环中。例如

int choice;
bool valid_input;

do
{
    cout << "Choose option 1,2 or 3: \n";
    cout << "1: Drop a single chip into one slot \n";
    cout << "2: Drop multiple chips into one slot \n";
    cout << "3: Quit the program \n";

    if ( !( cin >> choice ) ) break;

    valid-input  = 1 <= choice && choice <= 3;

    if  ( !valid_input )
    {
        cout << "Please enter 1 2 or 3 \n";
    }
} while ( !valid_input );

if ( valid_input )
{
    cout << "it worked. There was selected option " << choice << std::endl;
}

答案 2 :(得分:1)

  

我使用我的或操作员错了吗?

  

if(choice!= 1 || 2 || 3)

这才是真正的作用:

if ((choice != 1) || (2) || (3))

也就是说:“如果选择不等于1或真或假”。

这与执行if (true)相同。

您想要做的是:

if (choice != 1 && choice != 2 && choice != 3) { ... re-enter number }

答案 3 :(得分:-4)

你需要这个:

#include <iostream>
using namespace std;

int main() {

    cout << "Choose option 1,2 or 3: \n";
    cout << "1: Drop a single chip into one slot \n";
    cout << "2: Drop multiple chips into one slot \n";
    cout << "3: Quit the program \n";

    int choice;
    cin >> choice; 

    if  (choice != 1 || choice != 2 || choice != 3)
    {
        cout << "Please enter 1 2 or 3 \n";
        cin >> choice;
    }
    else 
    {
        out << "it worked \n";
    }
}