常用数学函数模板
cmath 库常用函数:绝对值、幂、开方、四舍五入
数学函数
cmath
abs
sqrt
pow
GESP2
#include <bits/stdc++.h>
using namespace std;
int main() {
// 绝对值
cout << abs(-5) << endl; // 5 (整数)
cout << fabs(-3.14) << endl; // 3.14 (浮点)
// 幂与开方
cout << pow(2, 10) << endl; // 1024.0
cout << sqrt(2) << endl; // 1.41421...
cout << cbrt(27) << endl; // 3.0 (立方根)
// 取整
cout << floor(3.7) << endl; // 3.0 (向下取整)
cout << ceil(3.2) << endl; // 4.0 (向上取整)
cout << round(3.5) << endl; // 4.0 (四舍五入)
// 最大最小
cout << max(3, 5) << endl; // 5
cout << min(3, 5) << endl; // 3
cout << max({1, 3, 2}) << endl; // 3 (C++11 初始化列表)
// 对数
cout << log2(1024) << endl; // 10.0
cout << log10(1000) << endl; // 3.0
// 格式化输出
cout << fixed << setprecision(2);
cout << 3.14159 << endl; // 3.14
return 0;
}
📖 要点说明
abs对整数,fabs对浮点数pow返回 double,转 int 可能有精度问题floor向下、ceil向上、round四舍五入
⚠️ 常见错误
pow(2,10)转 int 可能得 1023(浮点精度)abs传 double 结果不对,应用fabssetprecision需配合fixed才是小数位数