C# if else-if 語句

1、做用spa

用來處理多條件的區間性的判斷。blog

2、語法string

if(判斷條件)

{
       要執行的代碼;

}
else if(判斷條件)

{
      要執行的代碼;

}
else if(判斷條件)

{
       要執行的代碼;

}
else if(判斷條件)

{
       要執行的代碼;
}

........

else

{
       要執行的代碼;
} 

執行過程:it

  程序首先判斷第一個if所帶的小括號中的判斷條件,若是條件成立,也就是返回一個true,則執行該if所帶的大括號中的代碼,執行完成後,當即跳出if else-if結構。class

若是第一個if所帶的判斷條件不成立,也就是返回一個false,則繼續向下進行判斷,依次的判斷每個if所帶的判斷條件,若是成立,就執行該if所帶的大括號中的代碼,若是不成立,則繼續向下判斷,若是 每一個if所帶的判斷條件都不成立,就看當前這個if else-if結構中是否存在else。語法

若是有else的話,則執行else中所帶的代碼,若是沒有else,則整個 if-else if什麼都不作。else能夠省略。程序

3、流程圖im

 

 4、實例static

練習1】學員的結業考試成績評測,成績>=90:A,90>成績>=80:B,80>成績>=70:C,70>成績>=60:D,成績<60:Eimg

class Program
    {
        static void Main(string[] args)
        {        
            //學員的結業考試成績評測
            // 成績>=90:A
            //90>成績>=80:B
            //80>成績>=70:C
            //70>成績>=60:D
            //成績<60:E
             Console.WriteLine("請輸入學員的考試成績");
            int socre = Convert.ToInt32(Console.ReadLine());
            if (socre >= 90)
            {
                Console.WriteLine("A");
 
            }
            else if (socre >= 80)
            {
                Console.WriteLine("B");
            }
            else if (socre >= 70)
            {
                Console.WriteLine("C");
            }
            else if (socre >= 60)
            {
                Console.WriteLine("D");
            }
            else
            {
                Console.WriteLine("E");
            }
 
            Console.ReadKey();
 
        }
    }

 

【練習2】 比較3個數字的大小 不考慮相等

Console.WriteLine("請輸入第一個數字");
int numberOne = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("請輸入第二個數字");
int numberTwo = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("請輸入第三個數字");
int numberThree = Convert.ToInt32(Console.ReadLine());
 
//三種狀況 應該使用 if else-if來作
//若是第一個數字大於二個數字而且而大於三個數字
if (numberOne > numberTwo && numberOne > numberThree)
{
    Console.WriteLine(numberOne);
}
 
//若是第二個數字大於一個數字而且也大於三個數字
else if (numberTwo > numberOne && numberTwo > numberThree)
{
    Console.WriteLine(numberTwo);
}
 
//第三個數字大於第二個數字而且大於一個數字
else
{
    Console.WriteLine(numberThree);
}
Console.ReadKey();  
相關文章
相關標籤/搜索