#include <cmath> 是C++标准库中的数学头文件,提供了许多与数学相关的函数,例如三角函数、指数、对数、幂和常用数学常量等。这个头文件不需要额外安装,可以直接在代码中使用。
1.sqrt
sqrt(n) 是数学库cmath.h中的一个函数,用于求一个数的平方根。在C++中调用 sqrt(n) 的方式是,包含头文件 #include <cmath>,然后直接使用函数名调用 sqrt(n),其中 n 是一个数字。例如:
#include <iostream>
#include <cmath>
int main()
{
double n = 16.0;
double square_root = sqrt(n);
std::cout << "The square root of " << n << " is " << square_root << std::endl;
return 0;
}
那输出将会是
The square root of 16 is 4
2.fabs(x)
fabs(x) 是 C++ 标准库 <cmath> 中的一个函数,用于计算给定数字 x 的绝对值(即其正值)。该函数可以接受整数、浮点数或双精度浮点数作为参数,并返回其绝对值。
使用 fabs(x) 的方法是包含头文件 #include <cmath>,然后直接使用函数名调用 fabs(x),其中 x 是一个数字。例如:
#include <iostream>
#include <cmath>
int main()
{
int n = -5;
float f = -3.14;
double d = -10.5;
int absolute_n = fabs(n);
float absolute_f = fabs(f);
double absolute_d = fabs(d);
std::cout << "The absolute value of " << n << " is " << absolute_n << std::endl;
std::cout << "The absolute value of " << f << " is " << absolute_f << std::endl;
std::cout << "The absolute value of " << d << " is " << absolute_d << std::endl;
return 0;
}
那输出将会是
The absolute value of -5 is 5
The absolute value of -3.14 is 3.14
The absolute value of -10.5 is 10.5
需要注意的是,

本文详细介绍了C++标准库cmath中的数学函数,如sqrt()、fabs()、pow()、ceil()、floor()、round()以及sin(),cos(),tan(),强调了它们的使用方法和注意事项,包括参数类型和弧度单位的转换。

2461

被折叠的 条评论
为什么被折叠?



