簡體   English   中英

C++中的多個if-else

[英]Multiple if-else in C++

我對 C++ 中的多個 if-else 的簡單程序感到困惑。 編碼

下面給出。

include<iostream.h>
void main()
{
int i;
cout<<"Enter the number:";
if(i==1)
{
cout<<"Sunday";
}

if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
}

當我嘗試運行此代碼時,輸​​出顯示了這一點。

Enter the number:1
Sunday invalid key

所以我的問題是為什么雖然輸出是 True .. 卻執行 Else 部分的輸出? 請幫我 。 謝謝你

這是因為您實際上沒有“多個 if-else”。 你有一個if (沒有else ),然后是另一個if 兩者是獨立的。 你可能想要:

if(i==1)
{
    cout<<"Sunday";
}
else if(i==2)
{
    cout<<"Monday";
}
else
{
    cout<<" invalid input";
}

這確保了最后的else塊只在前面的條件都不滿足時才運行。

首先檢查i是否等於 1。 如果是,則打印“Sunday”。 if語句到那時就結束了。 之后您檢查(在單獨的if語句中) i是否等於 2,如果是,則打印“星期一”,如果不是,則打印“無效輸入”。 要獲得您想要的結果,請編寫

else if (i == 2)

只有在i不是 1 時才執行第二個if / else語句。

或者,您可能想要使用switch語句。

switch(i)
{
    case 1:
        cout << "Sunday";
        break;
    case 2:
        cout << "Monday";
        break;
    default:
        cout << "invalid input";
        break;
}

但是如果使用switch請不要忘記break

你有兩個不同的條件。 一種是:

if(i==1) {
    cout<<"Sunday";
} // this statement ends here.

另一個:

if(i==2) {
    cout<<"Monday";
} else {
    cout<<" invalid input";
}

i不是 2 時,第二個總是會導致" invalid input"

這段代碼有幾個錯誤。 我在這里解釋並修復了它-

#include<iostream.h>
void main()
{
    int i;
    cout<<"Enter the number:";
    cin >> i; //take the input number from the user
    if(i==1)
    {
        cout<<"Sunday";
    }    
    /* the i==1 and i==2 block will run separately unless you connect them with an else */
    else if(i==2) 
    {
        cout<<"Monday";
    }
    else
    {
        cout<<" invalid input";
    }
}

如果您想進行正確的處理,則必須輸入 else if:

if(i==1)
    cout<<"Sunday";
else if(i==2)
    cout<<"Monday";
else
    cout<<" invalid input";

使用 else if,第二個和第三個條件不處理,因為第一個條件已經有效。 在你的代碼中,是先處理第一個條件下的代碼,而不是因為輸入不等於2,所以處理else下的代碼。

這是因為您對相同的輸入使用了兩個分支語句

1.第一個 if() 語句檢查你的值是否等於 1

if(i == 1)
    std::cout << "Sunday"; // here you have print "Sunday for 1

2.然后你再次用另一個if-else語句檢查你的值

if(i == 2)
  std::cout << "Mondey";
else
  std::cout << "invalid input";  // here you have print "invalid input" 
                                 //since i is not equal to 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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