简体   繁体   English

有没有办法包含多个!=运算符?

[英]Is there a way to include multiple != operators?

I'm trying to make a system that outputs invalid if a variable does not equal whole number or decimal number. 我试图使系统在变量不等于整数或十进制数时输出无效。 The problem is, it outputs invalid when the variable is not equal to the first option instead of both options. 问题是,当变量不等于第一个选项而不是两个选项时,它输出无效。 Is there a fix for this? 有解决办法吗?

I have tried making it an if statement as well as an else if statement instead of separating them with &&. 我尝试过使其成为if语句以及else if语句,而不是用&&分隔它们。 It did not work. 这没用。

if (user_input != "whole number") {
    std::cout << "\nInvalid";
    goto label1;
  }
  else if (user_input != "decimal number") {
    std::cout << "\nInvalid";
    goto label1;
  }

It outputs invalid is decimal number is inputted. 输入十进制数时输出无效。

Your requirement is that the system should output invalid if the variable does not equal "whole number" or "decimal number". 您的要求是,如果变量不等于“整数”或“十进制数”,则系统应输出无效。

We can translate this directly into code. 我们可以将其直接转换为代码。 To emphasize how I translated the requirement, I'm using and and or , but the code would be identical if you wrote things the more conventional way, using && for and and || 为了强调我如何翻译需求,我使用andor ,但是如果您以更常规的方式编写内容,则将代码完全相同,对于and||使用&& for or . or

if(user_input != "whole number" and user_input != "decimal number") 
{
    std::cout << "\nInvalid";
    goto label1;
}

Alternatively, we could write: 或者,我们可以这样写:

if (not (user_input == "whole number" or user_input == "decimal number")) 
{
    std::cout << "\nInvalid";
    goto label1;
}

A readable way to do this, with real code: 一种可读的方式,用真实的代码:

bool invalid = ((typeid(var) != typeid(int)) && (typeid(var) != typeid(double)));
if(invalid)
    std::cout << "Invalid !" << std::endl;

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM