📅  最后修改于: 2020-09-25 08:03:47             🧑  作者: Mango
C++中的rint() 函数使用当前的舍入模式将参数舍入为整数值。当前的舍入模式由函数 fesetround()确定。
double rint(double x);
float rint(float x);
long double rint(long double x);
double rint(T x); // For integral type
rint() 函数采用单个参数,并返回double,float或long double类型的值。此函数在
rint() 函数采用单个参数值取整。
rint() 函数使用fegetround()指定的舍入方向将参数x舍入为整数值,并返回该值。默认情况下,舍入方向设置为“最接近”。可以使用fesetround() 函数将舍入方向设置为其他值。
#include
#include
#include
using namespace std;
int main()
{
// by default, rounding direction is to-nearest i.e. fesetround(FE_TONEAREST)
double x = 11.87, result;
result = rint(x);
cout << "Rounding to-nearest (" << x << ") = " << result << endl;
// upper value is taken for mid-way values
x = 11.5;
result = rint(x);
cout << "Rounding to-nearest (" << x << ") = " << result << endl;
// setting rounding direction to DOWNWARD
fesetround(FE_DOWNWARD);
x = 11.87;
result = rint(x);
cout << "Rounding downward (" << x << ") = " << result << endl;
// setting rounding direction to UPWARD
fesetround(FE_UPWARD);
x = 33.32;
result = rint(x);
cout << "Rounding upward (" << x << ") = " << result << endl;
return 0;
}
运行该程序时,输出为:
Rounding to-nearest (11.87) = 12
Rounding to-nearest (11.5) = 12
Rounding downward (11.8699) = 11
Rounding upward (33.3201) = 34
#include
#include
#include
using namespace std;
int main()
{
int x = 15;
double result;
// setting rounding direction to DOWNWARD
fesetround(FE_DOWNWARD);
result = rint(x);
cout << "Rounding downward (" << x << ") = " << result << endl;
return 0;
}
运行该程序时,输出为:
Rounding downward (15) = 15
对于整数值,应用rint 函数将返回与输入相同的值。因此,在实践中,它通常不用于积分值。