Do While 循环问题
do
{
cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
ch=getch();
} while ( ch !='q' || ch != 'Q');
为什么上面的代码不起作用而下面的代码却起作用?我以多种方式尝试在每个语句周围加上括号,编译器每次都会弹出错误,直到我像下面那样重新组合它们。我只是想知道为什么它会这样做。
do
{
cout << "Car is coming ... " << "[P]ay or [N]ot?" << endl;
ch=getch();
} while ( !(ch=='q' || ch=='Q') );
我使用 Visual Studio 2008 作为我的编译器; x86架构。
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; x86 architecture.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
了解德摩根定律
(不是 A)或(不是 B)
不同
与不 (A 或 B)。
Learn De Morgan's laws
(not A) or (not B)
is not the same as
not (A or B).
(ch != 'q' || ch != 'Q')
始终为 true:“ch
不等于'q'
或ch
不等于'Q'
”。(ch != 'q' || ch != 'Q')
is always true: "ch
is not equal to'q'
orch
is not equal to'Q'
".问题是您的布尔逻辑已关闭,并且两个
while
条件不相同。顶部将为每个可能的字符返回 true。底部将为除“q”和“Q”之外的每个字符返回 true
The problem is your boolean logic is off and the two
while
conditions are not the same.The Top will return true for every single character possible. The bottom will return true for every character except 'q' and 'Q'
我认为您希望在第一个示例中做到这一点:
您希望输入不是
q
并且不是Q
。I think you want this in your first example:
You want that the input is not
q
AND notQ
.!(ch=='q' || ch=='Q')
相当于ch!='q' && ch!='Q'
。另请参阅德摩根定律。!(ch=='q' || ch=='Q')
is equivalent toch!='q' && ch!='Q'
. See also De Morgan's laws.你把逻辑搞反了,这就是我否定它的作用。根据 DeMirgan 定律,
!(ch == 'Q' || ch == 'q')
与ch != 'Q' && 相同。 ch != 'q'
。由于 if 不能同时为
little q
和big Q
,因此while (ch != 'Q' || ch != 'q' )
没有意义,因为如果它是“Q”,那么它就不是“q”,反之亦然。You've got the logic backwards, that's my negating it works. By DeMirgan's laws,
!(ch == 'Q' || ch == 'q')
is the same asch != 'Q' && ch != 'q'
.Since a if it cannot be both
little q
andbig 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.当使用“!”反转所有逻辑时,您通过将条件运算符“==”反转为“!=”做得对,但忘记反转逻辑运算符“||”到“&&”。因此,这应该是正确的:
我使用 C#,因此虽然上面的代码可以工作,但我会使用它,因为它更容易阅读:
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:
I use C#, so while code above will work, I would have used this instead as it is easier to read: