[英]Do While Loop Question
do
{
cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
ch=getch();
} while ( ch !='q' || ch != 'Q');
Why will the code on top not work while the code below does?为什么上面的代码不起作用而下面的代码不起作用? I tried it with parenthesis around each statement in numerous ways and the compiler would pop an error every time until I regrouped them as I did below.我以多种方式尝试在每个语句周围加上括号,编译器每次都会弹出一个错误,直到我像下面那样重新组合它们。 I'm just wondering why it does this.我只是想知道为什么它会这样做。
do
{
cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
ch=getch();
} while ( !(ch=='q' || ch=='Q') );
I'm using Visual Studio 2008 as my compiler;我使用 Visual Studio 2008 作为我的编译器; x86 architecture. x86 架构。
(not A) or (not B) (非 A)或(非 B)
is not the same as不一样
not (A or B).不是(A 或 B)。
(ch != 'q' || ch != 'Q')
is always true: " ch
is not equal to 'q'
or ch
is not equal to 'Q'
". (ch != 'q' || ch != 'Q')
始终为真:“ ch
不等于'q'
或ch
不等于'Q'
”。
The problem is your boolean logic is off and the two while
conditions are not the same.问题是您的 boolean 逻辑关闭并且两个while
条件不一样。
The Top will return true for every single character possible. Top 将为每个可能的字符返回 true。 The bottom will return true for every character except 'q' and 'Q'除 'q' 和 'Q' 之外的每个字符的底部都将返回 true
I think you want this in your first example:我想你在你的第一个例子中想要这个:
ch !='q' && ch != 'Q'
You want that the input is not q
AND not Q
.您希望输入不是q
而不是Q
。
!(ch=='q' || ch=='Q')
is equivalent to ch!='q' && ch!='Q'
. !(ch=='q' || ch=='Q')
等价于ch!='q' && ch!='Q'
。 See also De Morgan's laws .另见德摩根定律。
You've got the logic backwards, that's my negating it works.你的逻辑倒退了,那是我否定它有效。 By DeMirgan's laws, !(ch == 'Q' || ch == 'q')
is the same as ch != 'Q' && ch != 'q'
.根据德米尔根定律, !(ch == 'Q' || ch == 'q')
与ch != 'Q' && ch != 'q'
相同。
Since a if it cannot be both little q
and big Q
at the same time, while (ch != 'Q' || ch != 'q')
doesn't make sense because if it is 'Q' then it won't be 'q', and vice versa.由于 a if 它不能同时是little q
和big Q
, while (ch != 'Q' || ch != 'q')
没有意义,因为如果它是 'Q' 那么它不会' t 是 'q',反之亦然。
When inverting all your logic using ',', you did right by reversing the conditional operators "==" to ".=", but you forgot to reverse the logical operators "||"使用“,”反转所有逻辑时,您通过将条件运算符“==”反转为“.=”是正确的,但是您忘记反转逻辑运算符“||” to "&&": Thus, this should be correct:到“&&”:因此,这应该是正确的:
while (ch!='q' && ch!='Q');
I use C#, so while code above will work, I would have used this instead as it is easier to read:我使用 C#,所以虽然上面的代码可以工作,但我会改用它,因为它更容易阅读:
while (ch.ToUpper() != 'Q');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.