iT邦幫忙

2025 iThome 鐵人賽

DAY 4
0
自我挑戰組

C++入門即放棄系列 第 4

[DAY4]選擇自己要的!

  • 分享至 

  • xImage
  •  

運算子

📌 對左右值做判斷的運算字

📌 結果都是布林值 (truefalse)

運算子 說明 範例
== 等於 1 == 1
!= 不等於 1 != 1
> 大於 2 > 1
< 小於 1 < 2
>= 大於或等於 1 >= 1
<= 小於或等於 1 <= 1

📌 小於等於和大於等於,只要其中一個成立就為正

📌 如2>=1 → true ,1>=1 →true

if / else

  • 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 → 換行

if / else if / else

  • 也稱為巢狀判斷
  • 適用於條件多於一個以上的時候
📌 #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 不能跳行 要在同一行

switch

  • 適合用於整數或字元判斷
  • 跟巢狀判斷類似
📌 #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 適合處理有明確選項,如選單或固定數值的判斷

📌 當能自己做抉擇的時候,不要讓自己後悔


上一篇
[DAY3]我會說話了!
下一篇
[DAY5]我陷入了輪迴!
系列文
C++入門即放棄5
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言