if 用於判斷條件是否成立, 讓電腦決定條件成立時該作什麼事, 不成立時又該作什麼事
完整語法
if (條件1)
{
}
else if (條件2)
{
}
else if (條件3)
{
}
else
{
}
上述的 else-if, 可以有多個, 也可以沒有. else只能有一個或者沒有
判斷式中, 只能是bool
實例
下面代碼, 演算薪資所得稅
請輸入薪資 – salary
0<=salary<20000 : 所得稅 6%
20001<=salary<40000 : 所得稅 6%
40001<=salary<60000 : 所得稅 7%
60001<=salary<80000 : 所得稅 8%
80001以上 : 所得稅 13%
請列印出薪資, 所得稅, 實領金額
static void Main(string[] args)
{
double rate = 0;
Console.Write("請輸入薪資 : ");
int salary = Int32.Parse(Console.ReadLine());
if (salary < 20000) rate = 0.06;
else if (salary < 40000) rate = 0.07;
else if (salary < 60000) rate = 0.08;
else if (salary < 80000) rate = 0.09;
else rate= 0.13;
Console.WriteLine("薪資 : {0}, 所得稅 : {1}, 實領 : {2}", salary, salary * rate, salary * (1 - rate));
}
If ()後面的工作若只有一行, 可以省略 “{}”
巢狀結構
int n1 = 1, n2 = 5, n3 = 8, maxValue;
if (n1 > n2){
if (n1 > n3){
maxValue = n1;
}
else
maxValue = n3;
}
else {
if (n2 > n3)
maxValue = n2;
else
maxValue = n3;
}
switch : 多項判斷
switch(int){
case a:
case b:
break;
case c:
break;
default:
break;
}
三元運算子 … ? … : …
price=(age<=10?20:(age<60?100:50));
邏輯運算子 && (and)
and 可結合二個條件狀況, 二者皆需成立, 結果才會成立. 底下以空姐錄取標準為例子, 年齡 age必需 <=40 而且身高 height 必需>=160, 二個條件都成立才錄取
static void Main(string[] args)
{
Console.Write("請輸入年齡 : ");
int age = Int32.Parse(Console.ReadLine());
Console.Write("請輸入身高 : ");
int height = Int32.Parse(Console.ReadLine());
if (age <= 40 && height >= 160) Console.WriteLine("錄取");
else Console.WriteLine("不錄取");
}
請注意 and 條件, 當第一條件不成立, 第二條件就不會執行, 因為第一條件不成立, 那整個組合就是不成立的. 這種設計可節省cpu資源
static void Main(string[] args)
{
int i = 10, j = 20;
if (i++>10 && j-- < 20)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
Console.WriteLine("i:{0}, j:{1}", i, j);
}
結果 :
false
i : 11, j : 20
邏輯運算子 || (or)
or 亦可結合二個條件狀況, 其中一項成立, 結果就會成立. 以下代碼以測速照像為例. 如果速度 speed>50 或者 闖紅燈, 就拍照
static void Main(string[] args)
{
Console.Write("請輸入速度 : ");
int speed = Int32.Parse(Console.ReadLine());
Console.Write("闖紅燈(0:no, 1:yes) : ");
int ran_light = Int32.Parse(Console.ReadLine());
if (speed > 50 || ran_light == 1) Console.WriteLine("拍照");
else Console.WriteLine("沒事");
}
請注意 or 條件, 當第一條件成立, 第二條件就不會執行, 因為第一條件成立, 那整個組合就是成立的. 這種設計也是為了節省cpu的資源
static void Main(string[] args)
{
int i = 10, j = 20;
if (++i>10 || --j < 20)
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
Console.WriteLine("i:{0}, j:{1}", i, j);
}
結果 :
true
i:11, j:20
真值表
and及or 的真值表如下圖

