注意:我使用的是C++
为什么我的一个“while”语句(“while”编号 1)仍然执行,而我放在其上方的另一个“while”语句(“while”编号 2)有效?这让我很困扰,因为虽然 'while' 数字 1 不是真的,但是 'while' 数字 2 是真的,但是 'while' 数字 1 仍然执行而不是 'while' 数字 2。任何人都可以帮助我,或解释这个吗?这是我的代码:
#include <iostream>
#include <string>
using namespace std;
void PancakeGlutton()
{
int answer;
cout << "Good morning!" << endl;
cout << "Would you like to enter pancake data? Press 1 to accept, press 2 to decline: ";
cin >> answer;
while (answer == 1) {
int totalPeople = 10;
int totalPancakes = 0;
int input;
int lowest = 100000;
int highest = 0;
for (int i = 9; i >= 0; --i) {
cout << "How many pancakes did you eat this morning? I will be asking this question " << i << " more times." << endl;
cin >> input;
totalPancakes += input;
if (input >= highest) {
highest = input;
}
if (input <= lowest) {
lowest = input;
}
}
double pancakeAverage = double(totalPancakes) / double(totalPeople);
cout << "The total number of pancakes eaten was " << totalPancakes << " pancakes " << endl;
cout << "The average number of pancakes eaten was " << pancakeAverage << " pancakes " << endl;
cout << "The highest number of pancakes eaten was " << highest << " pancakes" << endl;
cout << "The lowest number of pancakes eaten was " << lowest << " pancakes" << endl;
cout << "" << endl;
cout << "Do you want to enter more pancake data? Press 1 to accept, press 2 to decline: ";
cin >> answer;
}
// while number 1:
while (answer == 2) {
break;
}
// while number 2:
while (answer != 1 || answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}
}
int main()
{
PancakeGlutton();
system("PAUSE");
return EXIT_SUCCESS;
}
最佳答案
while (answer != 1 || answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}
必须是
while (answer != 1 && answer != 2) {
cout << "Error: please enter a valid answer. 1 or 2? ";
cin >> answer;
}
关于c++ - 为什么我的 'while' 语句之一在我的另一个 'while' 语句为真时执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32389534/