C++ 为什么我的if-else语句会滴落到第三个else?
我试图了解这个控件语法是如何工作的 注意:这是我的C++ 为什么我的if-else语句会滴落到第三个else?,c++,loops,if-statement,C++,Loops,If Statement,我试图了解这个控件语法是如何工作的 注意:这是我的int.main功能的一部分: while(cin >> Options){ if(Options == 1){ //If I enter '1' here it will output: "aHi.Else." cout << "a"; }else{ cout << "hi"; } if(Options == 2){ //If I enter '
int.main
功能的一部分:
while(cin >> Options){
if(Options == 1){ //If I enter '1' here it will output: "aHi.Else."
cout << "a";
}else{
cout << "hi";
}
if(Options == 2){ //If I enter '2' here it will output: "hiaElse."
cout << "a";
}else{
cout <<"Hi.";
}
if(Options == 3){ //If I enter '3' here it will output: "hiHi.a"
cout << "a";
}else{
cout << "Else." << endl;
}
}
while(cin>>选项){
如果(Options==1){//如果我在这里输入'1',它将输出:“aHi.Else。”
cout如果ifs
彼此不依赖,因此如果Options
不是1,它将执行第一个if
语句的else分支,即使Options是2或3。这同样适用于其他ifs。因为Options
只能是1或2或3(或其他),您将始终获得另一个if
s的else
输出
如果要将多个条件相互链接,可以链接else
和if
。在下面的示例中,最后一个else
仅在Options
既不是1,也不是2,也不是3时执行
while(cin >> Options){
if(Options == 1){
cout << "a";
}
else if(Options == 2){
cout << "b";
}
else if(Options == 3){
cout << "c";
}
else{
cout << "Hello";
}
}
ifs
互不依赖,因此如果Options
不是1,它将执行第一个if
语句的else分支,即使Options是2或3。这同样适用于其他ifs。因为Options
只能是1或2或3(或其他),您将始终获得另一个if
s的else
输出
如果要将多个条件相互链接,可以链接else
和if
。在下面的示例中,最后一个else
仅在Options
既不是1,也不是2,也不是3时执行
while(cin >> Options){
if(Options == 1){
cout << "a";
}
else if(Options == 2){
cout << "b";
}
else if(Options == 3){
cout << "c";
}
else{
cout << "Hello";
}
}
您希望这会做什么?为什么?使用switch
语句;或表格查找。您可以使用switch
语句,或将所有else
更改为else if(条件)
你希望它做什么,为什么?使用开关
语句;或查表。你可以使用开关
语句,或将所有其他
更改为其他,如果(条件)
非常感谢,这正是我要找的。非常感谢,这正是我要找的。