當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。