if 可用來判斷條件是否成立,並且依照條件成立與否,來執行不同的程式碼。語法如下:if (條件)
{
// 如果條件為真,執行這個程式碼區
}
if-else 如果判斷條件成立,則執行 if 的程式碼區塊;如果條件不成立,則執行 else 的程式碼區塊。語法如下:if (條件)
{
// 如果條件為真,執行這個程式碼塊
}
else
{
// 如果條件為假,執行這個程式碼塊
}
else if 陳述式。語法如下:if (條件1)
{
// 如果條件1為真,執行這個程式碼區塊
}
else if (條件2)
{
// 如果條件1為假且條件2為真,執行這個程式碼區塊
}
// ... 可以有多個 else if
else
{
// 如果以上條件都為假,執行這個程式碼區塊
}
Console.Write("temperature:"); // 提示使用者輸入溫度並顯示它於執行畫面上
int t = Convert.ToInt32(Console.ReadLine()); // 讀取使用者輸入並將其轉換為整數
if (t < 25)
{
Console.WriteLine("Today is Cold!");
}
if (t > 25)
{
Console.WriteLine("Today is Hot!");
}
if (t == 25)
{
Console.WriteLine("Today is Perfect!");
}
(以上分別有三種不同的執行結果)

<25】
>25】
=25】
Console.Write("age:"); // 提示使用者輸入並顯示它於執行畫面上
int age = Convert.ToInt32(Console.ReadLine()); // 讀取使用者輸入並將其轉換為整數
if (age >= 18)
{
Console.WriteLine("You are an adult!");
}
else
{
Console.WriteLine("You are not an adult!");
}

>=18】
<=18】
Console.Write("time:"); // 提示使用者輸入並顯示它於執行畫面上
int time = Convert.ToInt32(Console.ReadLine()); // 讀取使用者輸入並將其轉換為整數
if (time < 12)
{
Console.WriteLine("Good morning!");
}
else if (time < 18)
{
Console.WriteLine("Good afternoon!");
}
else
{
Console.WriteLine("Good evening!");
}
(以上分別有三種不同的執行結果)

<12】
>12 && <18】

※以上資料如有錯誤請多指教