Why is a condition like (0 < a < 5) always true?

前端 未结 4 908
庸人自扰
庸人自扰 2020-11-29 13:56

I implemented the following program in C

    #include 
    int main() 
    {
       int a  = 10 ; 
       if(0 < a < 5) 
       {
               


        
相关标签:
4条回答
  • 2020-11-29 14:23

    Since 0 is less than 10, 0 < a would always evaluates to 1 , which is less than 5, making 0 < a < 5 always true. Change your condition to

    if(0 < a && a < 5) {...}     
    
    0 讨论(0)
  • 2020-11-29 14:26

    Unlike Python (which has operator chaining), C evaluates the condition as:

    (0 < a) < 5
    

    The result of (0 < a) is either 0 or 1, both of which are less than 5, so the overall condition is true.

    In C, a range test must be written:

    0 < a && a < 5
    

    Note that the Python script:

    for a in range(-1,7):
      if 0 < a < 5:
        print a, " in range"
      else:
        print a, " out of range"
    

    produces the output:

    -1  out of range
    0  out of range
    1  in range
    2  in range
    3  in range
    4  in range
    5  out of range
    6  out of range
    

    The 'equivalent' C program using the same if condition would, of course, produce the answer 'in range' for each value.

    0 讨论(0)
  • 2020-11-29 14:26
      if(x<y<z)
    

    It actually is valid syntax, but it doesn't do what you want.

    Realize that x<y returns a bool, i.e. true or false. You then compare it against whatever value "z" has. So the intention of "x<y<z" looks wrong.

    It can be:

    if(x < y && y < z)
    
    0 讨论(0)
  • 2020-11-29 14:27

    Because 0 < a evaluates to 1.

    Use:

    a > 0 && a < 5

    if you want to test if a is greater than 0 and lower than 5.

    0 讨论(0)
提交回复
热议问题