向上取整(ceil
函数)
首先数学类的计算通常需要包含头文件 cmath,或者是math.h。
在 C++ 中,可以使用 ceil
函数来进行向上取整。与 Python 中的 math.ceil
函数类似。
单词ceil有装天花板的意思,可以联想到向上方取整,便于记忆。
ceil(num),既是num的向上取整。
向下取整(floor
函数)
在 C++ 中,可以使用 floor
函数进行向下取整。与 Python 中的 math.floor
函数类似。
单词floor有地板的意思,可以联想到向下方取整,便于记忆。
floor(num),既是num的向下取整。
四舍五入(round
函数)
在 C++ 中,可以使用 round
函数来进行四舍五入。round
函数将参数进行四舍五入,返回的结果是最接近原始数字的整数。
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double num = 10.5;
double a = floor(num);
double b = ceil(num);
double c = round(num);
cout << "初始数据: " << num<< endl;
cout << "向上取整: " << a << endl;
cout << "向下取整: " <<b << endl;
cout << "四舍五入: " << c << endl;
return 0;
}