📅  最后修改于: 2023-12-03 14:39:57.205000             🧑  作者: Mango
在C++标准库中,有许多函数可以处理数学上的操作。其中,nearint()函数可以将一个浮点数舍入到最接近的整数。本文将介绍nearint()函数的使用方法和注意事项。
double nearint(double x);
nearint()函数接收一个浮点数参数x,将其舍入到最接近的整数,并返回该整数。如果有两个整数都离x同等远,那么nearint()会返回离x更靠近正无穷大方向的整数。如果x为NaN或正负无穷大,则nearint()会返回相应的值。
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a = 3.7; // 小数值
double b = -2.9; // 负小数值
double c = 4.5; // 大于0.5的小数值
double d = -4.5; // 小于-0.5的小数值
cout << "nearint of " << a << " = " << nearint(a) << endl;
cout << "nearint of " << b << " = " << nearint(b) << endl;
cout << "nearint of " << c << " = " << nearint(c) << endl;
cout << "nearint of " << d << " = " << nearint(d) << endl;
return 0;
}
运行结果如下:
nearint of 3.7 = 4
nearint of -2.9 = -3
nearint of 4.5 = 4
nearint of -4.5 = -5