为什么 (0 < a < 5) 这样的条件总是成立?

2023-12-27

我用C实现了以下程序

    #include <stdio.h>
    int main() 
    {
       int a  = 10 ; 
       if(0 < a < 5) 
       {
          printf("The condition is true!") ; 
       }
       return 0 ; 
    }

为什么条件0<a<5总是回来true?


与 Python(它有操作符链接 https://docs.python.org/3/reference/expressions.html#comparisons),C 将条件评估为:

(0 < a) < 5

的结果(0 < a)要么是0,要么是1,两者都小于5,所以整体条件为真。

在 C 语言中,必须编写范围测试:

0 < a && a < 5

请注意,Python 脚本:

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

产生输出:

-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

使用相同的“等效”C 程序if当然,条件将为每个值生成“在范围内”的答案。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 (0 < a < 5) 这样的条件总是成立? 的相关文章

随机推荐