简体   繁体   English

逻辑 && 运算符

[英]Logical && operators

if ((a % 5) && (a % 11))
  printf("The number %d is divisible by 5 and 11\n", a);
else
  printf("%d number is not divisible by 5 and 11\n", a);

How will the logical && operator work if I don't add == 0 in the expression, if there is no remainder, will it look for the quotient?如果我不在表达式中添加== 0 ,逻辑&&运算符将如何工作,如果没有余数,它会寻找商吗? and the quotient will always be a non zero term so the programme will always return true.并且商将始终是非零项,因此程序将始终返回 true。

In your code在你的代码中

 if ((a % 5) && (a % 11))

is the same as是相同的

 if ( ((a % 5) != 0)  && ((a % 11) != 0 ) )

Any non-zero value is taken as TRUTHY .任何非零值都被视为TRUTHY

According to the C Standard (6.5.13 Logical AND operator)根据 C 标准(6.5.13 逻辑与运算符)

3 The && operator shall yield 1 if both of its operands compare unequal to 0; 3 如果 && 运算符的两个操作数都不等于 0,则 && 运算符应产生 1; otherwise, it yields 0. The result has type int.否则,它产生 0。结果的类型为 int。

In the expression used in the if statement在 if 语句中使用的表达式中

if ((a % 5) && (a % 11))

if each operand a % 5 and a % 11 is unequal to 0 then the expression evaluates to logical true.如果每个操作数a % 5a % 11不等于 0,则表达式的计算结果为逻辑真。 That is when a is not divisible by 5 and is not divisible by 11 then the expression evaluates to true and as a result a wrong message is outputted in this statement也就是说,当a不能被5整除并且不能被11整除时,表达式的计算结果为 true,结果在该语句中输出错误消息

printf("The number %d is divisible by 5 and 11\n", a);

To make the output correct you should change the expression in the if statement the following way.要使 output 正确,您应该按以下方式更改 if 语句中的表达式。 Pay attention to that you need also to change the message in the second call of printf.注意,printf的第二次调用也需要更改消息。

if ((a % 5 == 0) && (a % 11 == 0 ))
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    printf("The number %d is divisible by 5 and 11\n", a);
else
    printf("%d number is either not divisible by 5 or by 11\n", a);
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

@Saurav 's answer best describes about your problem. @Saurav的回答最能说明您的问题。 In addition to it, if you want a solution in case you are not in mood to add == 0 , then you could just simply use !除此之外,如果你想要一个解决方案,以防你不想添加== 0 ,那么你可以简单地使用! (NOT) operator: (非)运算符:

if (!(a % 5) && !(a % 11))

Now it will show divisible only when both of the expression has zero values (ie no remainder - like the number 55 ).现在,只有当两个表达式都具有零值(即没有余数 - 就像数字55 )时,它才会显示divisible

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

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