📌 對左右值做判斷的運算字
📌 結果都是布林值 (true
或 false
)
運算子 | 說明 | 範例 |
---|---|---|
== |
等於 | 1 == 1 |
!= |
不等於 | 1 != 1 |
> |
大於 | 2 > 1 |
< |
小於 | 1 < 2 |
>= |
大於或等於 | 1 >= 1 |
<= |
小於或等於 | 1 <= 1 |
📌 小於等於和大於等於,只要其中一個成立就為正
📌 如2>=
1 → true
,1>=
1 →true
if
判斷條件是否成立,執行{ }內程式else
當條件不成立時,執行{ }內程式📌 #include <iostream>
using namespace std;
int main()
{
int score;
cout << "輸入分數:";
cin >> score;
if (score >= 60)
cout << "及格!" << endl;
else
cout << "不及格!" << endl;
return 0;
}
📌 endl → 換行
📌 #include <iostream>
using namespace std;
int main()
{
int score;
cout << "分數:";
cin >> score;
if (score >= 90)
cout << "A" << endl;
else if (score >= 80)
cout << "B" << endl;
else if (score >= 70)
cout << "C" << endl;
else if (score >= 60)
cout << "D" << endl;
else
cout << "不及格" << endl;
}
📌 else if 不能跳行 要在同一行
📌 #include <iostream>
using namespace std;
int main()
{
int input;
cout << "輸入符號:" << endl;
cin >> option;
switch(option)
{
case 'A':
cout << "A" << endl;
break;
case 'B':
cout << "B" << endl;
break;
case 'C':
cout << "C" << endl;
break;
default:
cout << "其他" << endl;
}
}
透過比較運算子(==、!=、>、<、>=、<=)
判斷兩個數值或條件的關係
if / else
適合決定不同的執行方向
else if
適合處理條件很多時的判斷
switch
適合處理有明確選項,如選單或固定數值的判斷
📌 當能自己做抉擇的時候,不要讓自己後悔