简体   繁体   English

循环条件中逻辑运算符的使用

[英]Use of Logical Operator in Loop Condition

In the below given code, why the ||在下面给出的代码中,为什么|| logical doesn't work, instead the loop terminates specifically when && is used ?逻辑不起作用,而是循环在使用&&时特别终止?

int main() {
    char select {};
    do {
        cout<<"Continue the loop or else quit ? (Y/Q): ";
        cin>>select;
    } while (select != 'q' && select != 'Q'); // <--- why || (or) doesn't work here ??
    return 0;
}

This loop will go on while select is not q and it's not Q :这个循环将继续下去,而selectq 它不是Q

while (select != 'q' && select != 'Q'); 

This loop will go on while select is not q or it's not Q .select不是q它不是Q这个循环将继续。

while (select != 'q' || select != 'Q'); 

Since one of them must be true, it'll go on forever.既然其中之一必须是真的,它就会永远持续下去。

Examples:例子:

  1. The user inputs q用户输入q

select != 'q' evaluates to false select != 'q'计算结果为false
select != 'Q' evaluates to true select != 'Q'评估为true
false || true false || true evaluates to true false || true评估为true

  1. The user inputs Q用户输入Q

select != 'q' evaluates to true select != 'q'计算结果为true
select != 'Q' evaluates to false select != 'Q'评估为false
true || false true || false evaluates to true true || false评估为true

You want to terminate the loop when select is equal either to 'q' or 'Q' .您希望在 select 等于'q''Q'时终止循环。

The opposite condition can be written like相反的条件可以写成

do {
    cout<<"Continue the loop or else quit ? (Y/Q): ";
    cin>>select;
} while ( not ( select == 'q' || select == 'Q' ) );

If to open the parentheses then you will get如果打开括号,那么你会得到

do {
    cout<<"Continue the loop or else quit ? (Y/Q): ";
    cin>>select;
} while ( not( select == 'q' ) && not ( select == 'Q' ) );

that in turn is equivalent to这又相当于

do {
    cout<<"Continue the loop or else quit ? (Y/Q): ";
    cin>>select;
} while ( select != 'q' && select != 'Q' );

Consider the following diagrams:考虑以下图表:

在此处输入图片说明

The full ellipse are all characters.完整的椭圆都是字符。 The white dots is q and Q respectively.白点分别是qQ The black filled area depicts characters that will make the expression true .黑色填充区域描绘了使表达式true字符。 First line is select != 'q' && select != 'Q' , second line is select != 'q' || select != 'Q'第一行是select != 'q' && select != 'Q' ,第二行是select != 'q' || select != 'Q' select != 'q' || select != 'Q' . select != 'q' || select != 'Q'

&& means both conditions must be true . &&表示两个条件都必须为true The resulting black area is the overlap of the two areas on the left.产生的黑色区域是左侧两个区域的重叠部分。

|| means either of the conditions must be true .意味着其中一个条件必须为true The resulting black area is the sum of the two areas on the left.产生的黑色区域是左侧两个区域的总和。

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

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