条件检查如何在"if
"条件下执行?
int main()
{
int a = 0;
printf("Enter the numbern");
scanf("%d",&a);
if(-600 <= a <= 600)
{
printf("True");
}
else
{
printf("False");
}
return 0;
}
输出为"True"。请澄清在"如果"条件下发生了什么?
这不是在c中测试区间的方法。您应该使用if (-600 <= a && a <= 600)
。
测试(-600 <= a <= 600)
在C中与其对应的数学语句没有相同的含义,相反,它被编译器解释为(-600 <=a) <= 600
将首先对-600 <= a
到0
或1
求值,然后将其解释为整数,并在第二次测试中比较为小于600。
编译启用了所有警告的代码-Wall
是避免常见错误的好方法。对于这段代码,clang和gcc给出了不同的警告消息,但含义是相同的。
Clang:
so13.c:9:18: warning: result of comparison of constant 600 with boolean expression is always true [-Wtautological-constant-out-of-range-compare]
if(-600 <= a <= 600)
~~~~~~~~~ ^ ~~~
gcc:
so13.c: In function ‘main’:
so13.c:9:18: warning: comparison of constant ‘600’ with boolean expression is always true [-Wbool-compare]
if(-600 <= a <= 600)
^~
so13.c:9:13: warning: comparisons like ‘X<=Y<=Z’ do not have their mathematical meaning [-Wparentheses]
if(-600 <= a <= 600)
~~~~~^~~~