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


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

C++中的fegetround()函数用于获取当前舍入方向对应的浮点舍入宏的值。

fegetround() 函数在<cfenv> 头文件中定义。

fegetround()原型

int fegetround();

参数:

  • None

返回:

  • 成功时,fegetround() 函数返回说明当前舍入方向的浮点舍入宏。
  • 失败时返回负值。
舍入宏值
说明
FE_DOWNWARD 向下舍入
FE_TONEAREST 四舍五入到最接近的值
FE_TOWARDZERO 向零舍入
FE_UPWARD 向上舍入

示例:fegetround() 函数如何工作?

#include <iostream>
#include <cmath>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
using namespace std;

void print_current_rounding_direction()
{
    cout << "Current rounding method: ";
    switch (fegetround()) {
        case FE_TONEAREST:
            cout << "FE_TONEAREST";
            break;
        case FE_DOWNWARD:
            cout << "FE_DOWNWARD";
            break;
        case FE_UPWARD:
            cout << "FE_UPWARD";
            break;
        case FE_TOWARDZERO:
            cout << "FE_TOWARDZERO";
            break;
        default:
            cout << "unknown";
    };
    cout << endl;
}

int main(void)
{
    print_current_rounding_direction();
    cout << "6.2 -> " << rint(6.2) << endl;
    cout << "18.7 -> " << rint(18.7) << endl;

    fesetround(FE_UPWARD);
    print_current_rounding_direction();
    cout << "6.2 -> " << rint(6.2) << endl;
    cout << "19.7 -> " << rint(19.7) << endl;
    
    fesetround(FE_DOWNWARD);
    print_current_rounding_direction();
    cout << "6.2 -> " << rint(6.2) << endl;
    cout << "19.7 -> " << rint(19.7) << endl;

    return 0;
}

运行程序时,输出将是:

Current rounding method: FE_TONEAREST
6.2 -> 6
18.7 -> 19
Current rounding method: FE_UPWARD
6.2 -> 7
19.7 -> 20
Current rounding method: FE_DOWNWARD
6.2 -> 6
19.7 -> 19

相关用法


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