跳到正文

算法·理论

c++ <cmath> 库常用函数

__abandon_please__约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年6月23日
篇幅
约 4 分钟
获赞
1

版本

  1. v1当前

c++ <cmath> 库常用函数

1. 基本运算

函数描述实例
abs(x)abs(x) ∣x∣\lvert x \rvertabs(−5.3) = 5.3abs(-5.3) \:= \:5.3
fabs(x)fabs(x)∣x∣\lvert x \rvertfabs(−3.14)=3.14fabs(-3.14)=3.14
fmod(x,y)fmod(x, y)xmod  yx\mod{y}fmod(10.5,3.0)=1.5fmod(10.5, 3.0)=1.5
remainder(x,y)remainder(x, y)IEEEIEEE 标准的余数remainder(10.5,3)=−0.5remainder(10.5, 3)=-0.5
fmax(x,y)fmax(x, y)max⁡ a,b\max \:a, bfmax(2.0,3.5)=3.5fmax(2.0, 3.5)=3.5
fmin(x,y)fmin(x, y)min⁡ a,b\min \:a, bfmin(2.0,3.5)=2.0fmin(2.0, 3.5)=2.0

2. 指数与对数

函数描述示例
exp(x)exp(x)exe^xexp(1.0)≈2.71828 exp(1.0) ≈ 2.71828
exp2(x)exp2(x)2x2^xexp2(3.0)=8.0exp2(3.0) = 8.0
log(x)log(x) ln⁡x\ln{x}log(10.0)≈2.30259log(10.0) ≈ 2.30259
log10(x)log10(x)log⁡10x\log_{10}xlog10(100.0)=2.0 log10(100.0) = 2.0
log2(x)log2(x) log⁡2x\log_2xlog2(8.0)=3.0log2(8.0) = 3.0
pow(x,y)pow(x, y)xyx^ypow(2.0,3.0)=8.0pow(2.0, 3.0) = 8.0
sqrt(x)sqrt(x) x\sqrt{x}sqrt(9.0)=3.0sqrt(9.0) = 3.0
cbrt(x)cbrt(x) x3\sqrt[3]{x}cbrt(27.0)=3.0cbrt(27.0) =3.0

3. 三角函数(弧度制)

函数描述示例
sin(x)sin(x)sin⁡x\sin{x}sin(M−PI/2) = 1.0sin(M_-PI/2)\: =\: 1.0
cos(x)cos(x)cos⁡x\cos{x}cos(M−PI) =  −1.0cos(M_-PI)\:=\: \:-1.0
tan(x)tan(x)tan⁡x\tan{x}tan(M−PI/4) ≈ 1.0tan(M_-PI/4) \:≈ \:1.0
asin(x)asin(x)asin x\text{asin}\: x 或 sin⁡−1x\sin^{-1}xasin(1.0) = M−PI/2 asin(1.0)\:=\:M_-PI/2
acos(x)acos(x)acos x\text{acos}\: x 或 cos⁡−1x\cos^{-1}xacos(−1.0)=M−PIacos(-1.0)=M_-PI
atan(x)atan(x)atan x\text{atan}\: x 或 tan⁡−1x\tan^{-1}xatan(1.0)=M−PI/4 atan(1.0)=M_-PI/4
atan2(y,x)atan2(y, x)atanyx\text{atan}{\frac{y}{x}}或tan⁡−1yx\tan^{-1}{\frac{y}{x}}atan2(1.0,1.0)=M−PI/4 atan2(1.0, 1.0)=M_-PI/4

4. 双曲函数

函数描述示例
sinh(x)sinh(x)sinh⁡x \sinh x 或 ex−e−x2\frac{ e^x-e^{-x}}{2} sinh(0.0)=0.0sinh(0.0) = 0.0
cosh(x)cosh(x)cosh⁡x \cosh x 或 ex+e−x2\frac{e^x + e^{-x}}{ 2}cosh(0.0)=1.0cosh(0.0) = 1.0
tanh(x)tanh(x)tanh⁡x \tanh x或 ex+e−xex−e−x\frac{e^x + e^{-x}}{ e^x-e^{-x}}tanh(1.0)≈0.762tanh(1.0) ≈ 0.762

5. 取整与舍入

函数描述示例
ceil(x)ceil(x)⌈x⌉\lceil x \rceilceil(2.3)=3.0ceil(2.3) = 3.0
floor(x)floor(x)⌊x⌋ \lfloor x \rfloorfloor(2.9)=2.0floor(2.9) = 2.0
trunc(x)trunc(x)⌊x⌋ \lfloor x \rfloortrunc(−2.9)=−2.0trunc(-2.9) = -2.0
round(x)round(x)⌊x+0.5⌋\lfloor x+0.5 \rfloorround(2.5)=3.0round(2.5) = 3.0
lround(x)lround(x)⌊x+0.5⌋\lfloor x+0.5 \rfloorlround(2.5)=3L lround(2.5) = 3L

6. 其他函数

函数描述示例
hypot(x,y)hypot(x, y)x2+y2 \sqrt{x^2+y^2}hypot(3,4)=5.0 hypot(3, 4) = 5.0
erf(x)erf(x)erf(x) \text{erf}(x) 或2π∫0xe−t2dt\frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} dterf(1.0)≈0.8427erf(1.0) ≈ 0.8427
tgamma(x)tgamma(x)Γ(x)\Gamma (x)tgamma(5.0)=24.0tgamma(5.0) = 24.0

注意事项

1.角度单位:

三角函数使用弧度((需将角度转换为弧度,如degrees×M−PI÷180) degrees \times M_-PI \div 180)。

2.兼容性:

部分函数((如 exp2,log2)exp2, log2)需 C++11 或更高版本。

3.错误处理:

如输入无效值((如 sqrt(−1))sqrt(-1)),可能返回 NaNNaN 或触发域错误。

原文