简体   繁体   中英

Output of this C program i can't understand

I am revising C again and was making some test programs. 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.

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 . And 1 <= 2000.00 is true.

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 >= b) && (a <= c)

You're getting caught by the fact that in C, booleans are integers: either 0 or 1 .

So that line is interpreted left-to-right: First 0 <= 3000 , which is true so it ends up as 1 . Then that value is fed into the next half, (1) <= 2000 , which is obviously true.

It will prints the string in printf.

Because the condition is static.

The 0 is always less than 30000.000000. For the next condition the output of the first condition returns 1. it checks using the 1.

The second condition checking is 1 <= 2000.00. This condition is also true.

So, only this prints the string.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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