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


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++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。