📜  C++ lrint()

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

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

C++中的lrint() 函数使用当前的舍入模式将参数舍入为整数值。当前的舍入模式由函数 fesetround()确定。它类似于rint(),但返回long int

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

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

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

lrint()参数

lrint() 函数采用单个参数值取整。

lrint()返回值

lrint() 函数使用fegetround()指定的舍入方向将参数x舍入为整数值,并以long int返回值。

默认情况下,舍入方向设置为“最接近”。可以使用fesetround() 函数将舍入方向设置为其他值。

示例1:lrint()如何在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;
    long int result;
    result = lrint(x);
    cout << "Rounding to-nearest (" << x << ") = " << result << endl;
    
    // mid-way values are rounded off to higher integer
    x = 11.5;
    result = lrint(x);
    cout << "Rounding to-nearest (" << x << ") = " << result << endl;

    // setting rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    x = 11.87;
    result = lrint(x);
    cout << "Rounding downward (" << x << ") = " << result << endl;
    
    // setting rounding direction to UPWARD
    fesetround(FE_UPWARD);
    x = 33.32;
    result = lrint(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

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

#include 
#include 
#include 
using namespace std;

int main()
{
    int x = 15;
    long int result;
    
    // setting rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    result = lrint(x);
    cout << "Rounding downward (" << x << ") = " << result << endl;
    return 0;
}

运行该程序时,输出为:

Rounding downward (15) = 15

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