当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ lrint()用法及代码示例


C++ lrint() 函数

lrint() 函数是 cmath 头文件的库函数,用于对给定值进行四舍五入并将其转换为长整数。它接受一个值 (floatdouble, 或者long double) 并根据指定的舍入方向舍入后返回一个长整数值fegetround()函数。

lrint() 函数的语法:

C++11:

    long int lrint (double x);
    long int lrint (float x);
    long int lrint (long double x);
    long int lrint (T x); 

参数:

  • x– 表示要舍入的值。

返回值:

这个函数的返回类型是long int,它返回一个四舍五入到附近整数的长整数值。

例:

    Input:
    float x = 123.4f;
    
    Function call:
    lrint(x);
    
    Output:
    123

    Input:
    float x = 123.5f;
    
    Function call:
    lrint(x);
    
    Output:
    124

C++代码演示lrint()函数的例子

// C++ code to demonstrate the example of
// lrint() function

#include <iostream>
#include <cmath>
#include <fenv.h> // for fegetround()
using namespace std;

int main()
{
    float x = 0.0f;

    cout << "Specified rounding is:";
    switch (fegetround()) {
    case FE_DOWNWARD:
        cout << "Downward" << endl;
        break;
    case FE_TONEAREST:
        cout << "To-nearest" << endl;
        break;
    case FE_TOWARDZERO:
        cout << "Toward-zero" << endl;
        break;
    case FE_UPWARD:
        cout << "Upward" << endl;
        break;
    default:
        cout << "Unknown" << endl;
    }

    x = 123.4f;
    cout << "lrint(" << x << "):" << lrint(x) << endl;

    x = 123.5f;
    cout << "lrint(" << x << "):" << lrint(x) << endl;

    x = 123.6f;
    cout << "lrint(" << x << "):" << lrint(x) << endl;

    x = -123.4f;
    cout << "lrint(" << x << "):" << lrint(x) << endl;

    x = -123.5f;
    cout << "lrint(" << x << "):" << lrint(x) << endl;

    x = -123.6f;
    cout << "lrint(" << x << "):" << lrint(x) << endl;

    return 0;
}

输出

Specified rounding is:To-nearest
lrint(123.4):123
lrint(123.5):124
lrint(123.6):124
lrint(-123.4):-123
lrint(-123.5):-124
lrint(-123.6):-124

参考:C++ lrint() 函数



相关用法


注:本文由纯净天空筛选整理自 lrint() Function with Example in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。