gpt4 book ai didi

c - 这些运算符在 C 中做什么

转载 作者:行者123 更新时间:2023-11-30 21:26:15 24 4
gpt4 key购买 nike

我对 C 非常陌生,我正在查看一些示例代码,但我不确定 if 语句中的这些运算符在“询问”什么。

这是代码:

int main(void){

int a = 99;

int b = 0;

int c = 74;

if( a || b )
printf("first\n");

else
printf("second\n");

if( a && c )
printf("third\n");

else
printf("fourth\n");

if( !a )
printf("fifth\n");

else
printf("sixth\n");

if( (a && b) || c )
printf("seventh\n");

else
printf("eighth\n");

if( !c || !b )
printf("nineth\n");

else
printf("tenth\n");
}

我知道运算符的意思,只是不明白当他们执行“if”语句时发生了什么。有人可以向我解释一下吗?

最佳答案

回答这个问题的关键是了解C如何处理参与逻辑运算的整数:

  • 零被视为FALSE
  • 除零之外的所有值均被视为 TRUE

以下是代码片段中三个运算符的真值表:

!FALSE -> TRUE
!TRUE -> FALSE

FALSE || FALSE -> FALSE
FALSE || TRUE -> TRUE
TRUE || FALSE -> TRUE
TRUE || TRUE -> TRUE

FALSE && FALSE -> FALSE
FALSE && TRUE -> FALSE
TRUE && FALSE -> FALSE
TRUE && TRUE -> TRUE

当在不带括号的表达式中使用多个运算符时,一元 ! 将应用于二元 &&|| 之前。

现在您有足够的信息来自己计算输出。

关于c - 这些运算符在 C 中做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19041633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com