簡體   English   中英

為什么我的if-else陳述會落到其他第三條?

[英]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輸出。

你可以連續使用elseif ,如果你想多個條件相互鏈接。 在下面的示例中,僅當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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM