[英]Why does || operator work in my situation
Why is this an infinite loop using ||为什么这是使用 || 的无限循环logical operator
逻辑运算符
char c;
std::cin >> c;
while( c != 'y' || c != 'Y' || c != 'N' || c != 'n')
but this is not但这不是
while( c != 'y' && c != 'Y' && c != 'N' && c != 'n')
I don't understand why && operator work here because logically thinking ||我不明白为什么 && 运算符在这里工作,因为逻辑思考 || operator is better fit.
运营商更适合。
Lets just look at the very smallest part:让我们看看最小的部分:
c != 'Y' || c != 'N'
If c is 'Y' then it is not 'N', if it is 'N' then it is not 'Y'.如果 c 为“Y”则不是“N”,如果为“N”则不是“Y”。 Aka:
又名:
c | c != 'Y' || c != 'N'
Y | 1 || 0 = 1
N | 0 || 1 = 1
? | 1 || 1 = 1
If your logic always returns 1 no matter what, the loop will run forever.如果您的逻辑无论如何总是返回 1,则循环将永远运行。 I assume you are looking to wait until you get
c
as one of these values, so write it logically.我假设您希望等到将
c
作为这些值之一,因此请按逻辑编写。
I want to wait until c is one of ['y', 'Y', ...]
我想等到 c 是 ['y', 'Y', ...] 之一
And you might be able to write some nicer code:你也许可以写一些更好的代码:
std::array<char> options = {{'y', 'Y', 'n', 'N'}};
while (std::none_of(std::begin(options), std::end(options),
[&c](char check) { return check == c; };)) {
std::cout << "Hey write the correct character!\n";
}
Untested!未经测试!
You are checking the condition which is always true by using ||
您正在使用
||
检查始终为真的条件operator, ( c != 'y' || c != 'Y' || c != 'N' || c != 'n')
operator,
( c != 'y' || c != 'Y' || c != 'N' || c != 'n')
This is always true,because it would always satisfy at-least 3 conditions in your conditional statement.这始终是正确的,因为它始终会满足您的条件语句中的至少 3 个条件。
if your char is n
then it would satisfy remaining conditions c!='y'
, c!='Y'
, c!='N'
and similarly for any other character如果您的 char 是
n
那么它将满足其余条件c!='y'
, c!='Y'
, c!='N'
并且对于任何其他字符类似
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.