zero is greater than or equal to zero evaluates to

2019-07-24 14:33发布

问题:

i = 0;
if(0 <= i <= 0) 

this returns false.

I don't understand this at all. Watch window I also tried making the statement read (0 <= i && i <= 0) when I test them individually 0 <= i returns false while i <= 0 returns true. they both should be true. I'm not sure if this is a precision thing but I wouldn't think so since I'm hard coding the values in. Please help me understand this fundamental problem.

If it helps I am trying to evaluate if a point is on a line by getting the intersection point and then checking if it's between the x and y start point and end point. this becomes a problem when I am trying to check when x or y is on its axis then you run into the problem of checking if 0 is between or equal to 0 and 0. Which it is so it would fall on the line.

回答1:

Chaining of relational operators is not possible (to produce a valid result as per the expectation), you need to write separate instruction to verify each condition.

Due to the absence of explicit parenthesis and LTR association, a statement like

  if(0 <= i <= 0) 

is evaluated as

  if( (0 <= i) <= 0) 

which boils down to

  if ( 1 <= 0)

which produces a 0, (FALSE).

That said, the claim pertaining to

I also tried making the statement read (0 <= i && i <= 0) when I test them individually 0 <= i returns false while i <= 0 returns true. they both should be true

is not correct, they both are true. See for yourself