C++ 数学函数
在编程过程中,数学计算是一个非常常见的需求。C++提供了丰富的数学函数库,使我们能够轻松地进行各种数学计算。这些函数大多数都包含在<cmath>
头文件中,这是C++标准库的一部分。本文将介绍C++中常用的数学函数,并通过示例展示它们的使用方法。
引入数学函数库
在使用C++数学函数之前,我们需要首先引入<cmath>
头文件:
#include <iostream>
#include <cmath> // 引入数学函数库
int main() {
// 这里可以使用数学函数
return 0;
}
基本数学函数
绝对值函数
abs()
, fabs()
, labs()
, llabs()
函数用于计算一个数的绝对值。
#include <iostream>
#include <cmath>
int main() {
std::cout << "abs(-5) = " << abs(-5) << std::endl; // 整数绝对值
std::cout << "fabs(-3.14) = " << fabs(-3.14) << std::endl; // 浮点数绝对值
return 0;
}
输出:
abs(-5) = 5
fabs(-3.14) = 3.14
备注
abs()
用于整数类型,fabs()
用于浮点数类型,labs()
用于长整型,llabs()
用于长长整型。
向上/向下取整
ceil()
和floor()
函数分别用于向上和向下取整。
#include <iostream>
#include <cmath>
int main() {
std::cout << "ceil(3.2) = " << ceil(3.2) << std::endl; // 向上取整
std::cout << "ceil(-3.2) = " << ceil(-3.2) << std::endl; // 向上取整
std::cout << "floor(3.8) = " << floor(3.8) << std::endl; // 向下取整
std::cout << "floor(-3.8) = " << floor(-3.8) << std::endl;// 向下取 整
return 0;
}
输出:
ceil(3.2) = 4
ceil(-3.2) = -3
floor(3.8) = 3
floor(-3.8) = -4
四舍五入
round()
函数用于对数字进行四舍五入。
#include <iostream>
#include <cmath>
int main() {
std::cout << "round(3.2) = " << round(3.2) << std::endl; // 四舍五入
std::cout << "round(3.8) = " << round(3.8) << std::endl; // 四舍五入
std::cout << "round(-3.2) = " << round(-3.2) << std::endl;// 四舍五入
std::cout << "round(-3.8) = " << round(-3.8) << std::endl;// 四舍五入
return 0;
}
输出:
round(3.2) = 3
round(3.8) = 4
round(-3.2) = -3
round(-3.8) = -4