<cmath> 数学库和 <algorithm> 类似,C++ 提供了一个包含常见数学函数的工具库 <cmath>。引入后,求平方、开根号、取绝对值……一行函数调用就能搞定!
#include <cmath> // 引入数学库,之后就能用里面的函数了
⚠️ 使用 pow、sqrt、abs、ceil 前必须写 #include <cmath>,否则编译报 "undeclared" 错误。
绝对值 |x|:一个数在数轴上离零点的距离,结果总是非负。正数不变、负数去掉负号、零还是零。
// 过去要用 if 分支 if (a >= 0) { b = a; } else { b = -a; } // 引入数学库后,一行搞定 b = abs(a); // 求a的绝对值 b = fabs(a); // 浮点数也可以用fabs,效果一样
| 函数 | 用途 | 适用类型 |
|---|---|---|
| abs(x) | 求绝对值 | int / double 都可以 |
| fabs(x) | 求浮点数绝对值 | float / double(历史遗留,现代用 abs 即可) |
pow(a, b):计算 a 的 b 次幂,即 a^b。
exp2(b):特殊的 2 的幂,等价于 pow(2, b)。
double v = pow(2, 3); // 2的3次方 = 8 double r3 = pow(r, 3); // r的立方
sqrt(c):计算 c 的平方根(根号 c),等价于 pow(c, 1.0/2)。
double c = sqrt(25); // 根号25 = 5 double x = sqrt(a*a + b*b); // 勾股定理求斜边
⚠️ pow 和 sqrt 返回的都是 double 类型!sqrt 只能对非负数开方,sqrt(-1) 会得到 NaN。
log2(c):以 2 为底的对数(多少个 2 相乘等于 c)。
log10(c):以 10 为底的对数。
double x = log2(8); // = 3,因为2^3=8 double y = log10(1000); // = 3
| 函数 | 含义 | 3.2 | 3.8 | -3.2 |
|---|---|---|---|---|
| ceil(x) | 向上取整(天花板) | 4 | 4 | -3 |
| floor(x) | 向下取整(地板) | 3 | 3 | -4 |
| round(x) | 四舍五入 | 3 | 4 | -3 |
ceil(3.2); // 4 往大取 floor(3.8); // 3 往小取 round(3.5); // 4 四舍五入
💡 记忆口诀:ceil = 天花板(往上),floor = 地板(往下),round = 绕一圈(四舍五入)。
需要引入 <iomanip> 头文件:
#include <iomanip> double x = 3.14159265; cout << fixed << setprecision(2) << x << endl; // 输出:3.14(保留小数点后2位)
| 写法 | 效果 |
|---|---|
| setprecision(2) 不加 fixed | 保留 2 位有效数字(123.45→120) |
| fixed << setprecision(2) | 保留小数点后 2 位(123.45→123.45) |
⚠️ fixed 是"一次性"设置,写一次后后面所有 cout 浮点数都按这个精度。
不要手动写 3.14,精度太低!
double pi = acos(-1.0); // 精确求π ≈ 3.14159(机器精度) cout << fixed << setprecision(2) << pi << endl; // 3.14
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { double x = -3.14; cout << abs(x) << endl; // 3.14 cout << pow(2,10) << endl; // 1024 cout << sqrt(144) << endl; // 12 cout << ceil(3.2) << endl; // 4 cout << floor(3.8) << endl; // 3 cout << round(3.5) << endl; // 4 double pi = acos(-1.0); cout << fixed << setprecision(2) << pi << endl; return 0; }
4.0/3.0 或 (double)4/3。#include <cmath>!pow(10,2) 可能因浮点误差变成 99.999…,截断后变 99!整数幂最好用乘法 r*r*r。double pi = acos(-1.0);// 输入半径 r,输出球体积,保留4位小数 #include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { double r; cin >> r; double pi = acos(-1.0); // V = 4.0/3.0 * pi * pow(r, 3) ← 注意是4.0不是4 double v = 4.0/3.0 * pi * pow(r, 3); cout << fixed << setprecision(4) << v << endl; return 0; }
样例输入 1.5 → 输出 14.1372
double a, b; cin >> a >> b; double c = sqrt(a*a + b*b); cout << c << endl;
样例输入 3 4 → 输出 5
double x1,y1,x2,y2; cin >> x1 >> y1 >> x2 >> y2; double dx = x2-x1, dy = y2-y1; double dist = sqrt(dx*dx + dy*dy); cout << dist << endl;
样例输入 0 0 3 4 → 输出 5
#include <cmath>fixed << setprecision(n) 保留小数点后 n 位(需 <iomanip>)acos(-1.0),不要手写 3.14