的语句操作员无法正常工作

的语句操作员无法正常工作

本文介绍了“如果"带有“或"的语句操作员无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户选择不为1 2或3的数字,则尝试让我的程序输入用户租用人.
但是,无论何时键入1 2或3,它仍然希望我重新输入一个整数.我使用我或操作员的错误吗?

Trying to have my program make the user renter input if they choose a number that isn't 1 2 or 3.
However whenever I type 1 2 or 3 it still wants me to re enter an integer. Did I use my or operator wrong?

#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";
            }
}

推荐答案

这是因为您的 if :

choice != 1||2||3

正在评估:

int != int|| true || true

多数民众赞成在一定程度上是对的(或者是,或者是,是->是)

And thats always true (something OR yes OR yes -> yes)

强制转换为布尔值的每个非零整数( x!= 0 )值都将变为 true .

Every non-zero integer (x!=0) value casted to boolean will become true.

这是因为人类和计算机无法决定 1 的编号-您必须将其更改为 true false (是或否)

Its because humans and computers cant make decision on 1 number - you must change it to true or false (yes or no)

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

To resolve the problem simply change it to:

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

感谢@StillLearning的改进

Thanks to @StillLearning for improvements

这篇关于“如果"带有“或"的语句操作员无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:36