简体   繁体   English

这个 C 程序的输出我看不懂

[英]Output of this C program i can't understand

I am revising C again and was making some test programs.我正在再次修改 C 并且正在制作一些测试程序。 At one program I was checking a condition which was translating ino this condition.在一个程序中,我正在检查正在转换此条件的条件。

#include <stdio.h>
int main()
{
if(0 <= 3000.000000 <= 2000.00){  //this is the condition
printf("3000 is less than 2000, whoa.. \n");
}
return 0;
}

The output is always this print string.输出始终是此打印字符串。 I can't understand why.我不明白为什么。

PS聚苯乙烯

I am testing the middle value, ie 3000.000000 here, but it can be some variable.我在这里测试中间值,即 3000.000000,但它可以是一些变量。

The condition is parsed like this:条件解析如下:

if((0 <= 3000.000000) <= 2000.00){ 

The first part, (0 <= 3000.000000) , is true, and evaluates to 1 in the comparison with 2000.00 .第一部分(0 <= 3000.000000)为真,在与2000.00的比较中评估为1 And 1 <= 2000.00 is true. 1 <= 2000.00是真的。

If you're trying to test whether a value a lies between two values b and c or is equal to either, then you need an expression along the lines of如果您试图测试一个值a是否位于两个值bc或等于其中之一,那么您需要一个表达式

(a >= b) && (a <= c)

You're getting caught by the fact that in C, booleans are integers: either 0 or 1 .您会发现在 C 中,布尔值是整数: 01

So that line is interpreted left-to-right: First 0 <= 3000 , which is true so it ends up as 1 .所以该行从左到右解释:首先0 <= 3000 ,这是真的,所以它最终为1 Then that value is fed into the next half, (1) <= 2000 , which is obviously true.然后将该值送入下半部分, (1) <= 2000 ,这显然是正确的。

It will prints the string in printf.它将在 printf 中打印字符串。

Because the condition is static.因为条件是静态的。

The 0 is always less than 30000.000000. 0 总是小于 30000.000000。 For the next condition the output of the first condition returns 1. it checks using the 1.对于下一个条件,第一个条件的输出返回 1。它使用 1 进行检查。

The second condition checking is 1 <= 2000.00.第二个条件检查是 1 <= 2000.00。 This condition is also true.这个条件也成立。

So, only this prints the string.所以,只有这会打印字符串。

第一个条件评估为 1 作为输出,并进一步检查 1<2000 这也是真的。所以,字符串被打印出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM