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


C++ rint()用法及代碼示例

C++ rint() 函數

rint() 函數是 cmath 頭文件的庫函數。它用於將給定值四舍五入為基於指定方向的整數值fegetround()函數。它接受一個參數並返回四舍五入的值。

rint() 函數的語法:

C++11:

     double rint (double x);
      float rint (float x);
long double rint (long double x);
     double rint (T x); 

參數:

  • x– 表示要舍入的值。

返回值:

它返回四舍五入(到整數值)值。

例:

    Input:
    double x = 123.4;
    
    Function call:
    rint(x);
    
    Output:
    123

    Input:
    double x = 123.5;
    
    Function call:
    rint(x);
    
    Output:
    124

C++代碼演示rint()函數的例子

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

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

int main()
{
    double x = 0.0;

    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.4;
    cout << "rint(" << x << "):" << rint(x) << endl;

    x = 123.5;
    cout << "rint(" << x << "):" << rint(x) << endl;

    x = 123.6;
    cout << "rint(" << x << "):" << rint(x) << endl;

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

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

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

    return 0;
}

輸出

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

參考:C++ rint() 函數



相關用法


注:本文由純淨天空篩選整理自 rint() Function with Example in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。