一、作用
用來處理多條件的區間性的判斷。
二、語法
if(判斷條件)
{
要執行的代碼;
}
else if(判斷條件)
{
要執行的代碼;
}
else if(判斷條件)
{
要執行的代碼;
}
else if(判斷條件)
{
要執行的代碼;
}
........
else
{
要執行的代碼;
}
執行過程:
程序首先判斷第一個if所帶的小括號中的判斷條件,如果條件成立,也就是返回一個true,則執行該if所帶的大括號中的代碼,執行完成后,立即跳出if else-if結構。
如果第一個if所帶的判斷條件不成立,也就是返回一個false,則繼續向下進行判斷,依次的判斷每一個if所帶的判斷條件,如果成立,就執行該if所帶的大括號中的代碼,如果不成立,則繼續向下判斷,如果 每個if所帶的判斷條件都不成立,就看當前這個if else-if結構中是否存在else。
如果有else的話,則執行else中所帶的代碼,如果沒有else,則整個 if-else if什么都不做。else可以省略。
三、流程圖

四、實例
【練習1】學員的結業考試成績評測,成績>=90:A,90>成績>=80:B,80>成績>=70:C,70>成績>=60:D,成績<60:E
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();
