[英]Why does my if-else statements drip over towards the third else?
我試圖了解這種控制語法的工作方式。
注意:這是我的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;
}
}
為什么它會滴到else's
東西上? 語法有什么問題? 我糊塗了? 我應該如何使用不包含else's
語句的多個if
語句? 能給我舉個例子嗎?
ifs
彼此不依賴,因此,如果Options
值不是1,則即使Option是2或3,它也會執行第一個if
語句的else分支。其他ifs也是如此。 由於Options
只能是1或2或3(或其他值),因此if
s,您將始終獲得other的else
輸出。
你可以連續使用else
與if
,如果你想多個條件相互鏈接。 在下面的示例中,僅當Options
既不是1也不是2也不是3時,才執行最后一個else
。
while(cin >> Options){
if(Options == 1){
cout << "a";
}
else if(Options == 2){
cout << "b";
}
else if(Options == 3){
cout << "c";
}
else{
cout << "Hello";
}
}
或使用switch
語句:
while(cin >> Options){
switch(Options){
case 1:
cout << "a";
break;
case 2:
cout << "b";
break;
case 3:
cout << "c";
break;
default:
cout << "Hello";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.