这个嵌套的if
语句语法正确吗?
我正在尝试遍历所有值。但是它似乎没有提供任何输出,因为所有的值都不等于1。
我使用的是Xcode,所以有些代码可能与vs不同。
#include <iostream>
using namespace std;
int main() {
int haveMoney, haveTime, amHungry, restaurantOpen, haveTransportation;
cout << "Yes = 1, 2 = No" << endl << endl;
cout << "Do I have money?" << endl;
cin >> haveMoney;
cout << "Do I have time?" << endl;
cin >> haveTime;
cout << "Am I hungry?" << endl;
cin >> amHungry;
cout << "Are they open?" << endl;
cin >> restaurantOpen;
cout << "Do I have transportation?"<< endl;
cin >> haveTransportation;
if ((haveMoney == 1) && (haveTime == 1) && (amHungry == 1) && (restaurantOpen == 1) && (haveTransportation == 1)){
cout << "Enjoy your McDonalds!" << endl << endl;
if (haveMoney == 2){
cout << "You're broke, so you can't have McDonalds" << endl ;
if (haveTime == 2){
cout << "You don't have enough time to go to McDonalds!" << endl ;
if (amHungry == 2){
cout << "Why are you even thinking about McDonalds, you're not hungry!" << endl ;
if (restaurantOpen == 2){
cout << "McDonalds is closed, tough luck." << endl ;
if (haveTransportation == 2){
cout << "You have no transportation to get to McDonalds." << endl ;
}
}
}
}
}
}
return 0;
}
您需要链式if-else-if
语句,而不是嵌套的if
语句。这就是你所期望的。注意,为了方便输入,我省略了if
语句的花括号。
#include <iostream>
using namespace std;
int main() {
int haveMoney, haveTime, amHungry, restaurantOpen, haveTransportation;
cout << "Yes = 1, 2 = No" << endl << endl;
cout << "Do I have money?" << endl;
cin >> haveMoney;
cout << "Do I have time?" << endl;
cin >> haveTime;
cout << "Am I hungry?" << endl;
cin >> amHungry;
cout << "Are they open?" << endl;
cin >> restaurantOpen;
cout << "Do I have transportation?"<< endl;
cin >> haveTransportation;
if ((haveMoney == 1) && (haveTime == 1) && (amHungry == 1) && (restaurantOpen == 1) && (haveTransportation == 1))
cout << "Enjoy your McDonalds!" << endl << endl;
else if (haveMoney == 2)
cout << "You're broke, so you can't have McDonalds" << endl ;
else if (haveTime == 2)
cout << "You don't have enough time to go to McDonalds!" << endl ;
else if (amHungry == 2)
cout << "Why are you even thinking about McDonalds, you're not hungry!" << endl ;
else if (restaurantOpen == 2)
cout << "McDonalds is closed, tough luck." << endl ;
else if (haveTransportation == 2)
cout << "You have no transportation to get to McDonalds." << endl ;
return 0;
}