简体   繁体   中英

Logical expression in C

I am stuck at the following question from class. Using precedence, solve the following logical expression: 1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 9 / 10 > 0
I used the following steps to do the problem first
-> 1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 9 / 10 > 0
-> 1 && 3 - 4 < 5 && 6 <= 7 >= 8 != 1 > 0
-> 1 && -1 < 5 && 6 <= 7 >= 8 != 1 > 0
-> 1 && 1 && 1 >= 8 != 1 >0
-> 1 && 1 && 0 != 1 >0
-> 1 && 1 && 0 != 1
-> 1 && 1 && 1
-> 1 , so I suppose the answer is one, but when I try it using a C program, the answer is 0. (Code is shown below.)


#include <stdio.h>
int main(int argc, char* argv[]){
    int x = 1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 9 / 10 > 0;
    printf("1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 9 / 10 > 0 = %d\n", x);
    return 0;
}

In c, integer division does not do any rounding. So the 9/10 is 0 with 9 remainder, and the remainder is thrown out for the / operator (for the % operator, it's the other way around). This code results in a 1, like you would expect:

#include <stdio.h>
int main(int argc, char* argv[]){
    int x = 1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 10 / 10 > 0;
    printf("1 && -1 * -3 - 4 < 5 && 6 <= 7 >= 8 != 10 / 10 > 0 = %d\n", x);
    return 0;
}

Please take note the precedence of operators in C(it's like pemdas rule in math):

* / % + - << >> < <= > >= == != 

The right most expression

6 <= 7 >= 8 != 9 / 10 > 0 

is evaluated to be 0. And your using && logical expression so expect that for the whole expression the result will be 0.

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