简体   繁体   English

C语言中的逻辑表达式

[英]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 使用优先级,解决以下逻辑表达式: 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 && -1 * -3-4 <5 && 6 <= 7> = 8!= 9/10> 0
-> 1 && 3 - 4 < 5 && 6 <= 7 >= 8 != 1 > 0 -> 1 && 3-4-5 <&&6 <= 7> = 8!= 1> 0
-> 1 && -1 < 5 && 6 <= 7 >= 8 != 1 > 0 -> 1 && -1 <5 && 6 <= 7> = 8!= 1> 0
-> 1 && 1 && 1 >= 8 != 1 >0 -> 1 && 1 && 1> = 8!= 1> 0
-> 1 && 1 && 0 != 1 >0 -> 1 && 1 && 0!= 1> 0
-> 1 && 1 && 0 != 1 -> 1 && 1 && 0!= 1
-> 1 && 1 && 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.) -> 1,所以我想答案是1,但是当我使用C程序尝试时,答案是0。(代码如下所示)。


#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. 在c中,整数除法不进行任何舍入。 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). 因此9/10为0,余数为9,余数被/运算符抛出(对于%运算符,反之亦然)。 This code results in a 1, like you would expect: 这段代码的结果为1,就像您期望的那样:

#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): 请注意C中运算符的优先级(就像数学中的pemdas规则):

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

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. 计算为0。并且您使用&&逻辑表达式,因此期望整个表达式的结果为0。

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

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