简体   繁体   English

严格的价值比较(小于/大于)

[英]Strict Value Comparison (less/greater than)

I'm pretty sure that the following behaves incorrectly (at least, in my mind) because of some truthiness craziness: 我很确定以下行为不正确(至少在我的脑海中)因为一些真实的疯狂:

var x = 5;
0 < x < 10 // True, and returns true.
0 < x < 2 // False, and returns true.
0 < x < 0 // False, and returns false.

The way I figure it, the (0 < 5) is evaluating to true, and (true < 2) is also evaluating to true (ie, 1 < 2). 我的方法是,(0 <5)评估为true,(true <2)也评估为true(即1 <2)。 I tested this with the third statement, which seems to confirm my theory. 我用第三个语句对此进行了测试,这似乎证实了我的理论。 Now to the question: is there any way to make this 'work' without large amounts of extra code? 现在问的问题是:有没有办法让这个“工作”没有大量的额外代码?

"...is there any way to make this 'work' without large amounts of extra code?" “......有没有办法让这个'工作'没有大量的额外代码?”

Sure, use && ... 当然,使用&& ......

(0 < x) && (x < 10)

You can drop the parentheses if you want. 如果需要,可以删除括号。

As you have noticed most programming languages will not implement "between" as you would write it mathematically. 正如您所注意到的,大多数编程语言都不会实现“之间”,因为您将以数学方式编写它。 Instead separate the comparisons into two, where only two elements are compared each time. 而是将比较分成两部分,每次只比较两个元素。

var x = 5;
0 < x && x < 10
0 < x && x < 2
0 < x && x < 2

So, the first line reads "zero is less than x and x is less than ten". 因此,第一行显示“零小于x且x小于十”。 If you are uncertain about in which order the expression will be evaluated, will work as grouping. 如果您不确定表达式的评估顺序,将作为分组。

(0 < x) && (x < 10)

The problem stems from the fact that < is a binary operator. 问题源于<是二元运算符的事实。

Which means that one of the < gets evaluated at a time, not both. 这意味着其中一个<一次评估,而不是两者。

Which means that regardless of the order in which they are evaluated (which, IIRC is L to R), one of the comparisons will be wrong. 这意味着无论评估的顺序如何(IIRC是L到R),其中一个比较都是错误的。

Because this is CODE. 因为这是CODE。

Not ALGEBRA. 不是代数。

Otherwise, clever use of the && operator, as discussed by other answers, will make short work of your problem. 否则,巧妙地使用&&运算符,正如其他答案所讨论的那样,可以简化您的问题。

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

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