📜  C++附近的int()

📅  最后修改于: 2020-09-25 07:58:31             🧑  作者: Mango

C++中的neighborint() 函数使用当前的舍入模式将参数舍入为整数值。

C++中的neighborint() 函数使用当前的舍入模式将参数舍入为整数值。当前的舍入模式由函数 fesetround()确定。附近的int() 函数类似于rint(),不同之处在于它不会像rint()一样引发FE_INEXACT异常。

FE_INEXACT异常是一个浮点异常,当由于四舍五入或逐渐下溢而无法完全表示操作结果时,将发生此异常。

nearint()原型[从C++ 11标准开始]

double nearbyint(double x);
float nearbyint(float x);
long double nearbyint(long double x);
double nearbyint(T x); // For integral type

附近的int() 函数采用单个参数,并返回double,float或long double类型的值。此函数在头文件中定义。

附近的int()参数

附近的int() 函数将单个参数值取整。

nearint()返回值

附近的int() 函数使用fegetround()指定的舍入方向将参数x舍入为整数值,并返回该值。默认情况下,舍入方向设置为“最接近”。可以使用fesetround() 函数将舍入方向设置为其他值。

示例1:Centreintint()如何在C++中工作?

#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 = nearbyint(x);
    cout << "Rounding to-nearest (" << x << ") = " << result << endl;
    
    // upper value is taken for mid-way values
    x = 11.5;
    result = nearbyint(x);
    cout << "Rounding to-nearest (" << x << ") = " << result << endl;

    // setting rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    x = 17.87;
    result = nearbyint(x);
    cout << "Rounding downward (" << x << ") = " << nearbyint(x) << endl;
    
    // setting rounding direction to UPWARD
    x = 33.34;
    fesetround(FE_UPWARD);
    result = nearbyint(x);
    cout << "Rounding upward (" << x << ") = " << result << endl;
    
    return 0;
}

运行该程序时,输出为:

Rounding to-nearest (11.87) = 12 Rounding to-nearest (11.5) = 12 Rounding downward (17.87) = 17 Rounding upward (33.3401) = 34

示例2:整数类型的neighborint() 函数

#include 
#include 
#include 
using namespace std;

int main()
{
    int x = 15;
    double result;
    
    // setting rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    result = nearbyint(x);
    cout << "Rounding downward (" << x << ") = " << result << endl;

    return 0;
}

运行该程序时,输出为:

Rounding downward (15) = 15

对于整数值,应用nearbyint 函数将返回与输入相同的值。因此,在实践中,它通常不用于积分值。