#M8210. 常用数学函数
常用数学函数
数学函数
<cmath>
头文件中包含了很多数学函数,使用时应包含相关头文件:#include <cmath>
abs(x):求x的绝对值
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int a = -10;
cout << abs(a); // 输出为10
return 0;
}
pow(x, y):求x的y次幂
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int a = 2, b = 5;
cout << pow(a, b); // 输出为32
return 0;
}
sqrt(x):求x的平方根
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int a = 25;
cout << sqrt(a); // 输出为5
return 0;
}
ceil(x):求不小于x的最小整数(向上取整)
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int a = 5.1;
cout << ceil(a); // 输出为6
return 0;
}
floor(x):求不大于x的最大整数(向下取整)
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int a = 5.1;
cout << floor(a); // 输出为5
return 0;
}
round(x):将x四舍五入到最接近的整数
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double a = 5.5;
double b = 5.4;
cout << round(a) << endl;
cout << round(b);
// 结果为 6 5
return 0;
}
需要注意的是,这些函数在进行计算时都需要将参数转换为正确的数据类型,否则可能会出现不正确的结果。此外,对于大多数函数,它们的返回值都是浮点数类型。