有没有更紧凑的方法来检查一个数字是否在一个范围内?
我希望能够测试一个值是否在一个数字范围内.这是我当前的代码:
I want to be able to test whether a value is within a number range. This is my current code:
if ((year < 2099) && (year > 1990)){
return 'good stuff';
}
有没有更简单的方法来做到这一点?例如,有没有这样的东西?
Is there a simpler way to do this? For example, is there something like this?
if (1990 < year < 2099){
return 'good stuff';
}
推荐答案
在许多语言中,第二种方式会根据你想要的从左到右错误地评估.
In many languages, the second way will be evaluated from left to right incorrectly with regard to what you want.
例如,在 C 中,1990 <year
将评估为 0 或 1,然后变为 1 <2099
,当然,这总是正确的.
In C, for instance, 1990 < year
will evaluate to 0 or 1, which then becomes 1 < 2099
, which is always true, of course.
Javascript 与 C 非常相似:1990 <year
返回 true
或 false
,这些布尔表达式在数值上似乎分别等于 0 和 1.
Javascript is a quite similar to C: 1990 < year
returns true
or false
, and those boolean expressions seem to numerically compare equal to 0 and 1 respectively.
但是在 C# 中,它甚至不会编译,给你错误:
But in C#, it won't even compile, giving you the error:
错误 CS0019: 运算符 '<'不能应用于bool"和int"类型的操作数
error CS0019: Operator '<' cannot be applied to operands of type 'bool' and 'int'
你从 Ruby 得到一个类似的错误,而 Haskell 告诉你不能在同一个中缀表达式中使用 <
两次.
You get a similar error from Ruby, while Haskell tells you that you cannot use <
twice in the same infix expression.
在我的脑海中,Python 是我确定以这种方式处理中间"设置的唯一语言:
Off the top of my head, Python is the only language that I'm sure handles the "between" setup that way:
>>> year = 5
>>> 1990 < year < 2099
False
>>> year = 2000
>>> 1990 < year < 2099
True
最重要的是,第一种方式 (x < y && y < z)
始终是您最安全的选择.
The bottom line is that the first way (x < y && y < z)
is always your safest bet.
相关文章