[size=16.002px]以下是C++中常用的数学函数及其功能的表格,附带简单的案例说明: C++ 数学函数(需包含 <cmath> 头文件)函数名 功能描述 示例代码
sqrt(x) 计算 x 的平方根double x = sqrt(16); // x = 4.0
pow(x, y) 计算 x 的 y 次方double x = pow(2, 3); // x = 8.0
abs(x) 计算 x 的绝对值(适用于整数)int x = abs(-10); // x = 10
fabs(x) 计算 x 的绝对值(适用于浮点数)double x = fabs(-10.5); // x = 10.5
exp(x) 计算 e 的 x 次方double x = exp(1); // x ≈ 2.71828
log(x) 计算 x 的自然对数(以 e 为底)double x = log(2.71828); // x ≈ 1.0
log10(x) 计算 x 的以 10 为底的对数double x = log10(100); // x = 2.0
sin(x) 计算 x 的正弦值(x 为弧度)double x = sin(3.14159 / 2); // x ≈ 1.0
cos(x) 计算 x 的余弦值(x 为弧度)double x = cos(0); // x = 1.0
tan(x) 计算 x 的正切值(x 为弧度)double x = tan(3.14159 / 4); // x ≈ 1.0
asin(x) 计算 x 的反正弦值(返回值范围为 [-π/2, π/2])double x = asin(1); // x ≈ 1.5708 (π/2)
acos(x) 计算 x 的反余弦值(返回值范围为 [0, π])double x = acos(0); // x ≈ 1.5708 (π/2)
atan(x) 计算 x 的反正切值(返回值范围为 [-π/2, π/2])double x = atan(1); // x ≈ 0.7854 (π/4)
atan2(y, x) 计算 y/x 的反正切值(返回值范围为 [-π, π])double x = atan2(1, 1); // x ≈ 0.7854 (π/4)
ceil(x) 向上取整,返回不小于 x 的最小整数double x = ceil(3.2); // x = 4.0
floor(x) 向下取整,返回不大于 x 的最大整数double x = floor(3.9); // x = 3.0
round(x) 四舍五入,返回最接近 x 的整数double x = round(3.5); // x = 4.0
fmod(x, y) 计算 x 除以 y 的浮点余数double x = fmod(10.5, 3); // x = 1.5
hypot(x, y) 计算直角三角形的斜边长度(sqrt(x² + y²))double x = hypot(3, 4); // x = 5.0
max(x, y) 返回 x 和 y 中的较大值int x = max(3, 5); // x = 5
min(x, y) 返回 x 和 y 中的较小值int x = min(3, 5); // x = 3 示例代码:cpp
[backcolor=rgba(var(--ds-rgba-transparent))]复制
#include <iostream>#include <cmath> // 包含数学函数using namespace std;int main() { // 平方根 cout << "sqrt(16) = " << sqrt(16) << endl; // 幂次方 cout << "pow(2, 3) = " << pow(2, 3) << endl; // 绝对值 cout << "abs(-10) = " << abs(-10) << endl; cout << "fabs(-10.5) = " << fabs(-10.5) << endl; // 指数和对数 cout << "exp(1) = " << exp(1) << endl; cout << "log(2.71828) = " << log(2.71828) << endl; cout << "log10(100) = " << log10(100) << endl; // 三角函数 cout << "sin(π/2) = " << sin(3.14159 / 2) << endl; cout << "cos(0) = " << cos(0) << endl; cout << "tan(π/4) = " << tan(3.14159 / 4) << endl; // 反三角函数 cout << "asin(1) = " << asin(1) << endl; cout << "acos(0) = " << acos(0) << endl; cout << "atan(1) = " << atan(1) << endl; // 取整函数 cout << "ceil(3.2) = " << ceil(3.2) << endl; cout << "floor(3.9) = " << floor(3.9) << endl; cout << "round(3.5) = " << round(3.5) << endl; // 浮点余数 cout << "fmod(10.5, 3) = " << fmod(10.5, 3) << endl; // 斜边长度 cout << "hypot(3, 4) = " << hypot(3, 4) << endl; // 最大值和最小值 cout << "max(3, 5) = " << max(3, 5) << endl; cout << "min(3, 5) = " << min(3, 5) << endl; return 0;}
输出结果:
[backcolor=rgba(var(--ds-rgba-transparent))]复制
sqrt(16) = 4pow(2, 3) = 8abs(-10) = 10fabs(-10.5) = 10.5exp(1) = 2.71828log(2.71828) = 1log10(100) = 2sin(π/2) = 1cos(0) = 1tan(π/4) = 1asin(1) = 1.5708acos(0) = 1.5708atan(1) = 0.785398ceil(3.2) = 4floor(3.9) = 3round(3.5) = 4fmod(10.5, 3) = 1.5hypot(3, 4) = 5max(3, 5) = 5min(3, 5) = 3
[size=16.002px]这些函数是C++中常用的数学计算工具,涵盖了基本的算术运算、三角函数、对数函数、取整函数等。
|