我有一个问题。除了以下几行外,这里的所有内容似乎都运行良好:
} while (OneMoreTime != 'y' || OneMoreTime != 'n');
完整代码;
#include <iostream>
using namespace std;
int main()
{
int ARRAY_LENGTH = 5;
int MyArray[ARRAY_LENGTH] = {1, 2, 3, 4, 5};
cout << "Values in the array: " << ARRAY_LENGTH << endl;
for (char OneMoreTime = '\0'; OneMoreTime = 'n'; )
{
int WhichNumber = ARRAY_LENGTH;
do
{
cout << "What numbers from the array do you want to see, counting backwards? ";
cin >> WhichNumber;
} while ((WhichNumber > ARRAY_LENGTH) || (WhichNumber <= 0));
//calculating the correct position in the array (from start)
int Number2Print = ARRAY_LENGTH - WhichNumber;
//printing
cout << "The number is: " << MyArray[Number2Print] << endl;
//continue?
do
{
cout << "One more time? (y/n) ";
cin >> OneMoreTime;
} while (OneMoreTime != 'y' || OneMoreTime != 'n');
}
return 0;
}
我得到的是它不断要求&#34;再一次? (Y / N)&#34;在第一次成功打印后。如果我只使用一个条件它将起作用(但这不够)。
答案 0 :(得分:9)
该条件始终为真,因为OneMoreTime
不能同等于n
和y
。您可能的意思是使用&&
(和)
while (OneMoreTime != 'y' && OneMoreTime != 'n');
答案 1 :(得分:0)
这个声明 while(OneMoreTime!='y'|| OneMoreTime!='n'); 这是一个虚假的陈述,你会得到的是无论你投入什么都会回归真实 继续循环。
A || B,如果你输入'y',B是真的,如果你输'n',A是真的,所以如果其中一个条件为真,'或'操作将返回true。
如果你使用 while(OneMoreTime!='y'&amp;&amp; OneMoreTime!='n'); 如果输入'n'
,它仍然会在数组中放入下一个值