简体   繁体   English

为什么OR逻辑运算符(||)不起作用?

[英]Why doesnt the OR logical operator( || ) work?

I tried to use the OR logical operator in a do-while statement but for some reason it wouldn't work. 我试图在do-while语句中使用OR逻辑运算符,但由于某些原因,它不起作用。

It would work with no OR logical operators(only with one statement) but otherwise no. 它不使用OR逻辑运算符(仅使用一条语句),否则不起作用。

int main()
{
    char ansr;

    do
    {
        printf("What do you want to do?\n");
        printf("A = Add Employee\nR = Remove Employee\nE = Exit\n");
        scanf(" %c", &ansr);
    }while(ansr != 'E'||ansr != 'e');

    return 0;
}

Whenever i would write 'E' or 'e' I would expect the program to get out of the while loop but for some reason it would keep going through the do-while statement. 每当我写“ E”或“ e”时,我都希望程序退出while循环,但由于某种原因,它将继续执行do-while语句。

Logical OR (||) means "if either of these is true." 逻辑OR(||)表示“如果其中任何一个为真”。 In your case, if the input is not 'E' or it's not 'e' then it will perform another iteration. 在您的情况下,如果输入不是'E'或不是'e',则它将执行另一个迭代。 This is always true since even if it's one of them it's not going to be the other. 这始终是正确的,因为即使是其中之一,也不会是另一个。

You're probably thinking of logical AND (&&): 您可能正在考虑逻辑AND(&&):

while (ansr != 'E' && ansr != 'e');

This means "if both of these are true." 这意味着“如果这两个都是正确的”。 If ansr is either 'E' or 'e', one of the clauses will be false, and the whole expression will then become false. 如果ansr是'E'或'e',则其中一个子句将为false,然后整个表达式将为false。

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

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