標籤:一個 logs 執行 void strong code line write int
編寫多個if和編寫多謝if-esle if結果是不一樣的,下面以執行個體說明:
一、多個if-else if:
1 static void Main(string[] args) 2 { 3 int a = 5; 4 if (a > 1) 5 { 6 Console.WriteLine("a大於1"); 7 } 8 else if (a > 2) 9 {10 Console.WriteLine("a大於2");11 }12 else if (a > 3)13 {14 Console.WriteLine("a大於3");15 }16 else if (a > 6)17 {18 Console.WriteLine("a大於6");19 }20 else21 {22 Console.WriteLine("xx");23 }24 }
輸出:
a大於1
二、多個 if-if
1 static void Main(string[] args) 2 { 3 int a = 5; 4 if (a > 1) 5 { 6 Console.WriteLine("a大於1"); 7 } 8 if (a > 2) 9 {10 Console.WriteLine("a大於2");11 }12 if (a > 3)13 {14 Console.WriteLine("a大於3");15 }16 if (a > 6)17 {18 Console.WriteLine("a大於6");19 }20 else21 {22 Console.WriteLine("xx");23 }24 }
輸出:
a大於1
a大於2
a大於3
xx
三、總結
多個if - if 時,會執行每個if並判斷條件;
多個if - else if時,只會執行第一個合格;
else總是與最近的if配對。
C#中的if if...和if-else if