||, && C 中的运算符

||, && operators in C

为什么此代码仅适用于 && 运算符?

我认为应该是||,但我错了。 Choice 不能同时等于2个值?

我需要询问用户的输入,直到选择等于 'a''d',但为什么我需要写 &&?没看懂。

do
{
    scanf("%c", &choice);
} while ( choice != 'a' && choice != 'd' );

我想使用 ||,但它不起作用。

您可以使用 ||。你需要改变 while 循环条件表达式如下

while ( !(choice == 'a' || choice == 'd') ); 

只是DeMorgan's Law的一个应用,怎么不影响AND & OR

______   ___  ___
A || B =  A && B
______   ___  ___
A && B =  A || B

记为:"Break the line, change the sign".

INPUT   OUTPUT 1        OUTPUT 2
A   B   NOT (A OR B)    (NOT A) AND (NOT B)
0   0          1                 1
0   1          0                 0
1   0          0                 0
1   1          0                 0

INPUT   OUTPUT 1        OUTPUT 2
A   B   NOT (A AND B)   (NOT A) OR (NOT B)
0   0           1               1
0   1           1               1
1   0           1               1
1   1           0               0

你可以用这个替换条件:

while (!(choice == 'a' || choice == 'd'));

使用此条件 do-while 语句将一直执行到选择等于 'a' 或 'd'.

运算符的工作方式没有任何问题,您需要在此处获取代码的逻辑。

首先,只要 while 中的条件为真,do...while 循环就会运行。

在您的情况下,您希望询问用户的输入,直到选择等于 'a''d'

  • 所以,换句话说,只要用户输入不等于ad,就需要循环。

  • 从逻辑上讲,如果输入不等于a,它可以仍然等于d,所以你有检查那里的两种情况。只有当 adnone 是输入时,您才继续循环。

记住,您不是在检查相等性,而是在检查不等性。只有当两个不等式都满足时,只有 while 条件的计算结果为 TRUE_ 并且您继续循环以请求新值。

简而言之,read DeMorgan's laws.

嘿,它不会工作,因为你希望它不等于 a 和 b。

not equal to a and not equal to b

so it will be !( eqaul to a or eqaul to b) (De morgan's)

德摩根定律说

not( a and b)  = not (a) or not(b)

这里我简单地应用了那个。

如果要使用 or (||) 运算符,则必须应用 De Morgan's law:

假设 a 和 b 是布尔值,所以

a || b <=> !a && !b

a && b <=> !a || !b

这个,

while ( choice != 'a' && choice != 'd' );

相同
while !( choice == 'a' || choice == 'd' );

I need to ask user's input until choice will be equal to 'a' OR 'd'

这个条件可以这样写

choice == 'a' ||  choice == 'd'

因此,如果您希望循环迭代直到此条件为真,您应该编写

do
{
    //...
} while ( !( choice == 'a' ||  choice == 'd' ) );

或者如果要包含 header

#include <iso646.h> 

那你可以写

do
{
    //...
} while ( not ( choice == 'a' ||  choice == 'd' ) );

甚至喜欢

do
{
    //...
} while ( not ( choice == 'a' or  choice == 'd' ) );

条件

!( choice == 'a' ||  choice == 'd' )

not ( choice == 'a' or  choice == 'd' )

等同于

!( choice == 'a' ) &&  !( choice == 'd' )

not ( choice == 'a' ) and  not ( choice == 'd' )

反过来等同于

( choice != 'a' ) &&  ( choice != 'd' )

括号可以省略因此你将有

do
{
    //...
} while ( choice != 'a' &&  choice != 'd' );