1. 程式人生 > >C#中多重IF和巢狀IF

C#中多重IF和巢狀IF

1. 多重IF結構

如果IF條件需要分成多種情況時,將要用到多重IF條件的用法,即else if結構,這的語法如下:

If(條件1)

  

語句塊1;

   }

Else if(條件2)

  {

      語句塊2;

  }

.

Else if(條件n)

  {

  語句塊n;

  }

[else

 

語句塊n+1;

上面的結構就是把IF條件分成了n種情況進行判斷,符合某種條件則執行下面的程式碼。例如,如果滿足條件1,就執行語句塊1;如果條件滿足條件2,則執行語句2下的程式碼,依次判斷。如果條件均不滿足以上n種情況,那麼就執行else那麼部分的程式碼塊(else語句塊是可選擇的)。

下面來看個簡單的例子。

using System;

using System.Collections.Generic;

using System.Text;

namespace AddApp

{

classElseIfDemo

    {

publicstaticvoid Main()

        {

int month;

Console.WriteLine("請輸入某一個月份(1-12):");

            month=int.Parse(Console.ReadLine();

if(month<1)

            {

Console.WriteLine(

"您輸入的月份不正確!");

            }

elseif(month<=3)

            {

Console.WriteLine("您輸入的月份屬於第1個季度");

            }

elseif(month<=6)

            {

Console.WriteLine("您輸入的月份屬於第2個季度");

            }

elseif(month<=9)

            {

Console.WriteLine("您輸入的月份屬於第3個季度");

            }

elseif(month<=12)

            {

Console.WriteLine("您輸入的月份屬於第4個季度");

            }

else

            {

Console.WriteLine("您輸入的月份不正確!");

            }

}

}

}

在這個示例中使用else if結構判斷使用者輸入的月份屬於哪個季度,最後顯示判斷結果。如果使用者輸入的月份不正確(大於12或小於1),會顯示錯誤資訊。

   2.巢狀IF結構

當需要檢查多個條件時,應使用巢狀if結構,語示如下所示:

if (條件1)

            {

if(條件2)

                {

                    語句塊1;

                }

            }

            [else]

            {

if(條件3)

                {

                    語句塊2;

                }

else

                {

                    語句塊3;

                }

            }]

      當條件1的計算值為true時,檢查條件2,條件2的計算結果為true時,執行語句塊1。而如果條件1的計算結果為false時,檢查條件3;條件3的計算值為true時,執行語句塊2,否則執行語句塊3.

      下面來看個簡單的例子:

using System;

using System.Collections.Generic;

using System.Text;

namespace AddApp

{

classProgram

    {

staticvoid Main(string[] args)

        {

char ch;

float score;

Console.WriteLine("請輸入學生成績");

            score = float.Parse(Console.ReadLine());

if ((score < 0) || (score > 100))

            {

Console.WriteLine("你輸入的分數不對");

Console.ReadLine();

            }

else

            {

if (score >= 60)

                {

if (score >= 70)

                    {

if (score >= 80)

                        {

if (score >= 90)

                            {

Console.WriteLine("90分以上");

Console.ReadLine();

                            }

else

                            {

Console.WriteLine("80--90");

Console.ReadLine();

                            }

                        }

else

                        {

Console.WriteLine("70--80");

Console.ReadLine();

                        }

                    }

else

                    {

Console.WriteLine("60--70");

Console.ReadLine();

                    }

                }

else

                {

Console.WriteLine("不及格");

Console.ReadLine();

                }

            }

        }

    }

}

  上述例子用來對使用者輸入的分數時行判斷它所在那個分數段內。例如,如果使用者輸入75,那就會輸出70-80.

3.總結

不管使用什麼樣的方式進行判斷,就是要看你對條件的運用了。當條件之間有分支的時候,就用多重if語句,那條件之間有遞進關係的時候,就用巢狀if語句。