在C语言中指定IF条件内的范围
我只想知道这些C代码段之间的区别。我以两种不同的方式使用了它,最终输出不相同。
if(120<=units<160){
total= total- total*(15.0/100);
printf("Revenue : %.2f", total);
}
if(120<=units && units<160){
total= total- total*(15.0/100);
printf("Revenue : %.2f", total);
}
我们不能使用“ 120&lt; =单位&lt; 160”来指定C语言的范围?
I just want to know the difference between these C code segments. I used it in two different ways and final output was not same.
if(120<=units<160){
total= total- total*(15.0/100);
printf("Revenue : %.2f", total);
}
if(120<=units && units<160){
total= total- total*(15.0/100);
printf("Revenue : %.2f", total);
}
Can't we use "120<=units<160" to specify a range in C language?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,您不能以这种方式测试范围。这里发生的事情是按照操作员优先。
因此,这意味着:
(120&lt; =单位)&lt; 160
120&lt; =单位
的值如果为false或 1如果换句话说,完整的表达将始终是正确的,因为0和1均小于160。
No, you can't test ranges in this way. What's happening here is the operators are evaluated left-to-right as per operator precedence.
So this means:
(120 <= units) < 160
The value of
120 <= units
will be 0 if it is false or 1 if it is trueIn other words, the full expression will always be true, because both 0 and 1 are less than 160.
它被解析为这两个(我不记得哪一个)之一:
(120&lt; = units)&lt; 160
120&lt; =(单位&lt; 160)
在这两种情况下,都进行了一个比较,产生一个“ boolean”(
0
或1
)与其他数字进行比较,通常会导致“错误”结果(嗯,这是完全正确的,只是不符合您的期望)It's parsed as one of these two (I don't remember which):
(120 <= units) < 160
120 <= (units < 160)
In both cases, one comparison is done, yielding a "boolean" (
0
or1
) which is then compared with the other number, typically leading to a "wrong" result (well, it's perfectly correct, just doesn't match your expectation)这个问题类似于C ++的帖子。您可以参考下面链接中的帖子。 https://stackoverflow.com/a/3831148/19395482
The question is similar to a post in C++. You can refer to the post in the link below. https://stackoverflow.com/a/3831148/19395482
By Matthieu M.: