[英]Why is a condition like (0 < a < 5) always true?
I implemented the following program in C 我在C中实现了以下程序
#include <stdio.h>
int main()
{
int a = 10 ;
if(0 < a < 5)
{
printf("The condition is true!") ;
}
return 0 ;
}
Why does the condition 0<a<5
always return true
? 为什么条件
0<a<5
总是返回true
?
Unlike Python (which has operator chaining ), C evaluates the condition as: 与Python(具有运算符链接 )不同,C将条件评估为:
(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. (0 < a)
的结果是0或1,两者都小于5,因此整体条件为真。
In C, a range test must be written: 在C中,必须编写范围测试:
0 < a && a < 5
Note that the Python script: 请注意Python脚本:
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. 当然,使用相同
if
条件的“等效”C程序会为每个值产生“范围内”的答案。
Because 0 < a
evaluates to 1
. 因为
0 < a
计算结果为1
。
Use: 采用:
a > 0 && a < 5
if you want to test if a
is greater than 0
and lower than 5
. 如果你想测试
a
是否大于0
且小于5
。
Since 0
is less than 10
, 0 < a
would always evaluates to 1
, which is less than 5
, making 0 < a < 5
always true
. 因为
0
小于10
, 0 < a
总是计算结果为1
,这是小于5
,使得0 < a < 5
总是true
。 Change your condition to 把你的病情改为
if(0 < a && a < 5) {...}
if(x<y<z)
It actually is valid syntax, but it doesn't do what you want. 它实际上是有效的语法,但它没有做你想要的。
Realize that x<y
returns a bool, ie true or false. 意识到
x<y
返回一个bool,即true或false。 You then compare it against whatever value "z" has. 然后将它与“z”的值进行比较。 So the intention of "
x<y<z
" looks wrong. 所以“
x<y<z
”的意图看起来不对。
It can be: 有可能:
if(x < y && y < z)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.