常用函式
C++ 中的函式庫,存有不少好用的函式,善加利用可以節省不少時間,但還是要先明白該如何撰寫再使用
最大值、最小值
先試著撰寫一段能輸出最小值的程式碼吧
先輸入 n,再輸入 n 個數,輸出其中的最小值
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
在 <algorithm> 中,最大值最小值的函式是 max(x,y) 跟 min(x,y),用法如下
一定要注意的是,x 和 y 的型別要相同,一方為 int 時另一方不可以是 long long 型態,也別忘了在上方要 #include <algorithm>
在宣告最大值或最小值的變數時,要避免使用 max 和 min,因為這是函式的名稱,盡量不要重複使用,可用 ma、mi 或是其他名稱替代
最大公因數
輸入 a 和 b,輸出 a 跟 b 的最大公因數(ps. 運用輾轉相除法)
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
在 <algorithm> 中,有最大公因數的函式 __gcd(x,y) (gcd 前有兩個底線)
同樣也要注意兩個變數的型別要相同,否則程式會出錯
絕對值
輸入一個整數 n,輸出 n 的絕對值
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
絕對值的函式 abs(x) 在 <cmath> 中。
然而 abs 預設值是 int,如果要輸出的值大於 int ,會發生下圖情況
Image Not Showing
Possible Reasons
- The image file may be corrupted
- The server hosting the image is unavailable
- The image path is incorrect
- The image format is not supported
Learn More →
若變數型態是 long,就要使用 labs(n)
但 cmath 中沒有 long long 型態的 abs,因此要引入函式庫 <cstdlib> 才能使用 llabs(n)

交換兩數
輸入 a 和 b,將 a 與 b 的值交換後輸出。

交換兩數的函式是 swap(a,b) ,也要注意兩個要被交換的變數型態必須相同。