📜  C++ fesetexceptflag()

📅  最后修改于: 2020-09-25 07:16:19             🧑  作者: Mango

C++中的fesetexceptflag() 函数将指定的浮点异常标志从指针对象设置到浮点环境中。

fesetexceptflag() 函数在头文件中定义。

fesetexceptflag()原型

int fesetexceptflag( const fexcept_t* flagp, int excepts );

fesetexceptflag() 函数尝试将由excepts指定的所有浮点异常标志的内容从flagp复制到浮点环境中。

该函数仅修改标志,不会引发任何异常。

fesetexceptflag()参数

Bitmask accepted macros
Macro Type Description
FE_DIVBYZERO Pole error Division by zero
FE_INEXACT Inexact Not exact results such as (1.0/3.0)
FE_INVALID Domain error At least one arguments used is a value for which the function is not defined
FE_OVERFLOW Overflow range error Result is too large in magnitude to be represented by the return type
FE_UNDERFLOW Underflow range error Result is too small in magnitude to be represented by the return type
FE_ALL_EXCEPT All exceptions All exceptions supported by the implementation

fesetexceptflag()返回值

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

#include 
#include 
#pragma STDC FENV_ACCESS ON
using namespace std;

void print_exceptions()
{
    cout << "Raised exceptions: ";
    if(fetestexcept(FE_ALL_EXCEPT))
    {
        if(fetestexcept(FE_DIVBYZERO))
            cout << "FE_DIVBYZERO ";
        if(fetestexcept(FE_INEXACT))
            cout << "FE_INEXACT ";
        if(fetestexcept(FE_INVALID))
            cout << "FE_INVALID ";
        if(fetestexcept(FE_OVERFLOW))
            cout << "FE_OVERFLOW ";
        if(fetestexcept(FE_UNDERFLOW))
            cout << "FE_UNDERFLOW ";
    }
    else
        cout << "None";

    cout << endl;
}

int main()
{
    fexcept_t excepts;
    feraiseexcept(FE_DIVBYZERO);
    
    /* save current state*/
    fegetexceptflag(&excepts,FE_ALL_EXCEPT);
    print_exceptions();
    feraiseexcept(FE_INVALID|FE_OVERFLOW);
    print_exceptions();
    
    /* restoring previous exceptions */
    fesetexceptflag(&excepts,FE_ALL_EXCEPT);
    print_exceptions();
    
    return 0;
}

运行该程序时,输出为:

Raised exceptions: FE_DIVBYZERO
Raised exceptions: FE_DIVBYZERO FE_INVALID FE_OVERFLOW
Raised exceptions: FE_DIVBYZERO