📜  C++ llrint()

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

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

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

当前的舍入模式由函数 fesetround()确定。它类似于lrint(),但返回long long int而不是long int。

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

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

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

llrint()参数

llrint() 函数将单个参数值取整。

llrint()返回值

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

默认情况下,舍入方向设置为'to-nearest'

可以使用fesetround() 函数将舍入方向设置为其他值。

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

    // setting rounding direction to DOWNWARD
    fesetround(FE_DOWNWARD);
    x = 11.87;
    result = llrint(x);
    cout << "Rounding downward (" << x << ") = " << result << endl;
    
    // setting rounding direction to UPWARD
    fesetround(FE_UPWARD);
    x = 33.32;
    result = llrint(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:整数类型的llrint() 函数

#include 
#include 
#include 
using namespace std;

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

运行该程序时,输出为:

Rounding downward (15) = 15

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