有没有更紧凑的方法来检查数字是否在范围内? [英] Is there a more compact way of checking if a number is within a range?
问题描述
我希望能够测试一个值是否在数字范围内.这是我当前的代码:
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<年份
的值为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.
这篇关于有没有更紧凑的方法来检查数字是否在范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!