一、比较函数
min(a, b) – 返回最小值
#include <algorithm>
int a = 5, b = 10;
int smaller = min(a, b); // 返回5
max(a, b) – 返回最大值
#include <algorithm>
int a = 5, b = 10;
int larger = max(a, b); // 返回10
扩展用法:
min({a, b, c, d}); // 返回最小值
max({a, b, c, d}); // 返回最大值
二、交换函数
swap(a, b) – 交换两个值
#include <utility> // 或 <algorithm>
int x = 5, y = 10;
swap(x, y); // x=10, y=5
三、数学函数<cmath>
1. 绝对值
// 整数绝对值
int a = -5;
int abs_a = abs(a);
// 浮点数绝对值
double b = -3.14;
double abs_b = abs(b);
2. 平方根 – sqrt(a)
double x = 16.0;
double root = sqrt(x); // 4.0
3. 立方根 – cbrt(a)
double x = 27.0;
double root = cbrt(x); // 3.0
4. 求幂 – pow(a, b)
double a = 2.0, b = 3.0;
double result = pow(a, b); // 8.0 (2³)
// 实际应用:
pow(10, 2) // 100.0
pow(2, 0.5) // √2 ≈ 1.414
pow(4, -1) // 0.25 (4⁻¹)
四、取整函数<cmath>
1. ceil(a) – 向上取整
#include
ceil(3.2) // 4.0
ceil(-3.2) // -3.0
ceil(3.0) // 3.0
2. floor(a) – 向下取整
#include <cmath>
floor(3.8) // 3.0
floor(-3.8) // -4.0
floor(3.0) // 3.0
3. round(a) – 四舍五入
#include <cmath>
round(3.4) // 3.0
round(3.5) // 4.0
round(-3.5) // -4.0 (中间值向远离0方向舍入)
4. trunc(a) – 截断小数部分(向0取整)
#include <cmath>
trunc(3.7) // 3.0
trunc(-3.7) // -3.0
trunc(3.0) // 3.0
实用示例
示例1:最大公约数和最小公倍数
int a,b;
cin>>a>>b;
int p=1;
for(int i=2;i<=min(a,b);i++){
if(a%i==0&&b%i==0){
p=i;
}
}
cout<<p; // 最大公约数
int q=a*b/p;
cout<<q; // 最小公倍数
示例2:判断质数
int n;
cin>>n;
bool f=true;
for(int i=2;i<=sqrt(n);i++){
if(n%i==0){
f=false;
break;
}
}
if(f){
cout<<"yes";
}
else{
cout<<"no";
}
示例3:求最大值
#include <bits/stdc++.h>
using namespace std;
int main(){
int a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
cout<<max({a,b,c,d,e});
return 0;
}
示例4:求a的b次方
#include <bits/stdc++.h>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
int k=round(pow(a,b));
cout<<k;
return 0;
}
示例5:验证完全平方数
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin>>n;
int k=round(sqrt(n));
if(k*k==n){
cout<<"yes";
}
else{
cout<<"no";
}
return 0;
}