简体   繁体   中英

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). 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". 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.

Because this is CODE.

Not ALGEBRA.

Otherwise, clever use of the && operator, as discussed by other answers, will make short work of your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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