tags: tgirc早修book

常用函式

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 →

#include <iostream> using namespace std; int main(){ int n,num; cin >> n >> num; int mi=num; n-=1; while(n--){ cin >> num; if(num < mi){ mi=num; } } cout << mi <<'\n'; return 0; }

<algorithm> 中,最大值最小值的函式是 max(x,y)min(x,y),用法如下

#include <iostream> #include <algorithm> using namespace std; int main(){ int n,num; cin >> n >> num; int mi=num; n-=1; while(n--){ cin >> num; mi = min(num,mi); } cout << mi <<'\n'; return 0; }

一定要注意的是,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 →

#include <iostream> using namespace std; int main(){ int a,b; cin >> a >> b; while(b != 0){ a%=b; int tmp=a; a=b; b=tmp; } cout << a <<'\n'; return 0; }

<algorithm> 中,有最大公因數的函式 __gcd(x,y) (gcd 前有兩個底線)
同樣也要注意兩個變數的型別要相同,否則程式會出錯

#include <iostream> #include <algorithm> using namespace std; int main(){ int a,b; cin >> a >> b; cout << __gcd(a,b) <<'\n'; return 0; }

絕對值

輸入一個整數 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 →

#include <iostream> using namespace std; int main(){ int n; cin >> n; if(n < 0){ cout << -n <<'\n'; } else{ cout << n << '\n'; } return 0; }

絕對值的函式 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)

#include <iostream> #include <cmath> #include <cstdlib> using namespace std; int main(){ long long n; cin >> n; cout<<llabs(n)<<'\n'; return 0; }

交換兩數

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

#include <iostream> using namespace std; int main(){ int a, b, temp; cin >> a >> b; temp = a; //使用temp避免a的值被覆蓋掉 a = b; b = temp; cout << "a=" << a << " b=" << b; return 0; }

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

#include <iostream> using namespace std; int main(){ int a,b; cin >> a >> b; swap(a, b); cout << "a=" << a << " b=" << b; return 0; }