C++ 标准库提供了丰富的功能,其中 <cmath> 是一个包含数学函数的头文件,它提供了许多基本的数学运算和常数。
<cmath> 是 C++ 标准库中的一个头文件,它定义了一组数学函数,这些函数可以执行基本的数学运算,如幂运算、三角函数、对数、绝对值等。
要使用 <cmath> 中的函数,你需要在你的 C++ 程序中包含这个头文件:
#include <cmath>
常用函数
<cmath> 提供了许多数学函数,以下是一些常用的函数。
1. 基本数学函数
abs(x)
x
abs(-5) // 5
fabs(x)
fabs(-5.5) // 5.5
fmod(x, y)
y
fmod(5.3, 2) // 1.3
remainder(x, y)
remainder(5.5, 2) // 1.5
fmax(x, y)
fmax(3.5, 4.2) // 4.2
fmin(x, y)
fmin(3.5, 4.2) // 3.5
hypot(x, y)
sqrt(x*x + y*y)
hypot(3, 4) // 5
2. 指数和对数函数
exp(x)
e^x
e
exp(1) // 2.71828...
log(x)
log(2.71828) // 1
log10(x)
log10(100) // 2
pow(x, y)
pow(2, 3) // 8
sqrt(x)
sqrt(16) // 4
cbrt(x)
cbrt(27) // 3
expm1(x)
e^x - 1
expm1(1) // 1.71828...
log1p(x)
log(1 + x)
log1p(0.00001) // 0.00001
3. 三角函数
sin(x)
sin(3.14159 / 2) // 1
cos(x)
cos(3.14159) // -1
tan(x)
tan(0) // 0
asin(x)
asin(1) // 3.14159/2
acos(x)
acos(-1) // 3.14159
atan(x)
atan(1) // 3.14159/4
atan2(y, x)
y/x
atan2(1, 1) // 3.14159/4
4. 双曲函数
sinh(x)
sinh(0) // 0
cosh(x)
cosh(0) // 1
tanh(x)
tanh(1) // 0.7616
asinh(x)
asinh(1) // 0.8814
acosh(x)
acosh(1) // 0
atanh(x)
atanh(0.5) // 0.5493
5. 取整和浮点数操作
ceil(x)
ceil(2.3) // 3
floor(x)
floor(2.3) // 2
trunc(x)
trunc(2.8) // 2
round(x)
round(2.5) // 3
lround(x)
long
lround(2.5) // 3
llround(x)
long long
llround(2.5) // 3
nearbyint(x)
nearbyint(2.5) // 2
rint(x)
rint(2.5) // 3
modf(x, &intpart)
modf(2.3, &intpart)
6. 浮点数检查
isfinite(x)
isfinite(3.0) // true
isinf(x)
isinf(1.0 / 0.0) // true
isnan(x)
isnan(0.0 / 0.0) // true
isnormal(x)
isnormal(1.0) // true
signbit(x)
signbit(-5.3) // true
实例
下面是一个使用 <cmath> 的简单示例,展示了如何计算一个数的平方根、正弦值和绝对值。
#include <iostream>#include <cmath> // 包含 <cmath> 头文件 int main() { double num = 9.0; double root = sqrt(num); // 计算平方根 double sinValue = sin(M_PI / 2); // 计算正弦值,M_PI 是 π 的近似值 double absValue = abs(-5.0); // 计算绝对值 std::cout << "The square root of " << num << " is " << root << std::endl; std::cout << "The sine of " << M_PI / 2 << " is " << sinValue << std::endl; std::cout << "The absolute value of -5.0 is " << absValue << std::endl; return 0;}
输出结果:
The square root of 9 is 3 The sine of 1.570796 is 1 The absolute value of -5 is 5
实例2
#include <iostream>#include <cmath> int main() { // 基本数学运算 std::cout << "abs(-5) = " << abs(-5) << std::endl; std::cout << "fmod(5.3, 2) = " << fmod(5.3, 2) << std::endl; // 指数和对数函数 std::cout << "exp(1) = " << exp(1) << std::endl; std::cout << "log(2.71828) = " << log(2.71828) << std::endl; std::cout << "pow(2, 3) = " << pow(2, 3) << std::endl; // 三角函数 std::cout << "sin(3.14159 / 2) = " << sin(3.14159 / 2) << std::endl; std::cout << "cos(3.14159) = " << cos(3.14159) << std::endl; // 取整函数 std::cout << "ceil(2.3) = " << ceil(2.3) << std::endl; std::cout << "floor(2.3) = " << floor(2.3) << std::endl; // 浮点数检查 double x = 1.0 / 0.0; if (isinf(x)) { std::cout << "x is infinite" << std::endl; } return 0;}
注意事项
<cmath> 是 C++ 标准库中一个非常有用的头文件,它提供了许多基本的数学函数,可以帮助开发者在编写程序时进行数学运算。