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


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

C++ 中的fesetround() 函數嘗試設置指定的浮點舍入方向,該方向應為浮點舍入宏之一。

fesetround() 函數在<cfenv> 頭文件中定義。

fesetround()原型

int fesetround( int round );

此函數采用單個參數 round ,它是浮點舍入宏之一。然後嘗試將round 設置為浮點舍入方向。

參數:

  • round:舍入方向,是浮點舍入宏之一。回合的可能值為FE_TONEAREST、FE_DOWNWARD、FE_UPWARD、FE_TOWARDZERO。

返回:

  • 成功時,fesetround() 函數返回 0。
  • 失敗時,它返回非零。

示例:fesetround() 函數如何工作?

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