【发布时间】:2014-12-15 05:04:18
【问题描述】:
早些时候,在一个 IRC 频道上,有人问了一个关于他的代码的问题 - 本质上,他的程序在无限循环中运行:
#include <iostream>
using namespace std;
int main()
{
cout << "This program adds one to your input." << endl;
char choice = 'n';
int num = 0;
while (choice != 'y' || choice != 'Y')
{
cout << "Enter number: ";
cin >> num;
num++;
cout << "Your number plus 1 is: " << num << endl;
cout << endl << "Continue/Quit? Type 'Y' to quit, any other key to continue: ";
cin >> choice;
}
cout << "By choosing 'Y', you exit the loop." << endl;
return 0;
}
注意循环头,看起来循环应该工作得很好,但是每当我输入 Y 或 y 以退出时,循环就会继续运行。考虑到如果左边的表达式为真,while 循环不会计算右边的表达式,这使得它特别令人困惑。但无论如何,即使我输入 Y 或 y 循环也会继续运行!我想对为什么会发生这种情况进行一些深入的解释,我一直在试图找出原因,回顾我的教科书等,但我似乎无法理解为什么......我已经改变了 OR变成 AND,但是是什么让 OR 如此糟糕并导致它出现故障?
谢谢大家。
【问题讨论】:
-
更加注意
while(...)条件的逻辑。大声朗读几遍。考虑这个类似的情况:如果你不是男性,或者你不是女性,那么你就不能加入俱乐部(俱乐部最终没有会员)。
标签: c++ operators computer-science