C++ Math
C++ Math
C++ 有很多功能,可以让你在 Math 上执行数学任务。
Max 与 min
max(x,y) 函数可用于查找 x 和 y 的最大值:
实例
#include <iostream>using namespace std;int main() {cout << max(5, 10);return 0;}
min(x,y) 函数可以用来求 x 和 y 的最小值:
实例
#include <iostream>using namespace std;int main() {cout << min(5, 10);return 0;}
C++ <cmath> Header
其他函数,如 sqrt(平方根)、round(四舍五入一个数字)和 log(自然对数),都在 <cmath> 头文件中:
实例
#include <iostream>#include <cmath>using namespace std;int main() {cout << sqrt(64) << "\n";cout << round(2.6) << "\n";cout << log(2) << "\n";return 0;}
其他 Math 函数
下表列出了其他流行的 Math 数学函数(来自 <cmath> 库):
| 函数 | 描述 |
|---|---|
| abs(x) | 返回 x 的绝对值 |
| acos(x) | 返回 x 的反余弦值 |
| asin(x) | 返回 x 的反正弦值 |
| atan(x) | 返回 x 的反正切值 |
| cbrt(x) | 返回 x 的立方根 |
| ceil(x) | 返回 x 的值,将其向上舍入到最接近的整数 |
| cos(x) | 返回 x 的余弦值 |
| cosh(x) | 返回 x 的双曲余弦值 |
| exp(x) | 返回 Ex 的值 |
| expm1(x) | 返回 ex -1 |
| fabs(x) | 返回浮动 x 的绝对值 |
| fdim(x, y) | 返回 x 和 y 之间的正差值 |
| floor(x) | 返回向下舍入到最接近整数的 x 值 |
| hypot(x, y) | 返回 sqrt(x2 +y2) |
| fma(x, y, z) | 返回 x*y+z 不失精准 |
| fmax(x, y) | 返回浮点 x 和 y 的最大值 |
| fmin(x, y) | 返回浮点 x 和 y 的最小值 |
| fmod(x, y) | 返回 x/y 的浮点余数 |
| pow(x, y) | 返回 x 的 y 次幂 |
| sin(x) | 返回 x 的正弦值(x 以弧度为单位) |
| sinh(x) | 返回双精度值的双曲正弦只 |
| tan(x) | 返回角度的切线 |
| tanh(x) | 返回双精度值的双曲正切值 |