形式:
if (運算式)
{
執行陳述式
}
只有運算式值為真或非 0 時,大括號內陳述式才執行。if-else 成對,但有時只有 if 無 else。範例:
double x;
Console.WriteLine("輸入一個數字:");
string data = Console.ReadLine();
x = Convert.ToDouble(data);
if (x > 1000)
{
Console.WriteLine("x 好大");
}
else if (x > 100)
{
Console.WriteLine("x > 100");
}
else if (x > 0)
{
Console.WriteLine("x 大於 0 小於 100");
}
else
{
Console.WriteLine("x < 0");
}
Console.WriteLine(x);
輸入 135 結果:x > 100。
if (x > 1000)
{
if (x == 9000) Console.WriteLine("x = 9000");
if (x == 8000) Console.WriteLine("x = 8000");
if (x > 5000) Console.WriteLine("x > 5000");
Console.WriteLine("x 好大");
}
編譯器逐條判斷,滿足條件才執行。if-else-if 處理多分支,但分支多時巢狀層數多,程式龐大且難理解。
基本用法:
switch (運算式)
{
case 常數運算式1:
陳述式1; break;
case 常數運算式2:
陳述式2; break;
...
case 常數運算式n:
陳述式n; break;
}
範例:
public static void week()
{
Console.WriteLine("輸入整數 1-4:");
string xingqi = Console.ReadLine();
int day = Convert.ToInt32(xingqi);
switch (day) // day 型別不能為 float 等非整數
{
case 1: Console.WriteLine("Monday"); break;
case 2: Console.WriteLine("Tuesday"); break;
case 3: Console.WriteLine("星期三"); break;
case 4: Console.WriteLine("星期四"); break;
}
Console.ReadKey();
}
字串也可作 switch:
string str = Console.ReadLine();
switch (str)
{
case "hi": Console.WriteLine("hi"); break;
case "hello": Console.WriteLine("hello"); break;
}
若 case "hi" 不加 break,會貫穿執行下一 case:
switch (str)
{
case "hi":
case "hello": Console.WriteLine("hello"); break;
}
輸入 hi 會輸出 hello。請親自編程體會。