📜  C++ feclearexcept()

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

C++中的feclearexcept() 函数尝试清除参数excepts指定的浮点异常标志。

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

feclearexcept()原型

int feclearexcept(int excepts);

为了使该函数正常工作,您应该启用FENV_ACCESS ,这将使您的程序能够访问浮点环境以测试所引发的异常。

feclearexcept()参数

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

feclearexcept()返回值

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

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

int main()
{
    // clears all exceptions
    feclearexcept(FE_ALL_EXCEPT);
    cout << "1/0 = " << 1.0/0.0 << endl;
    
    // tests if above statement raised the FE_DIVBYZERO exception
    if(fetestexcept(FE_DIVBYZERO))
    {
        cout << "FE_DIVBYZERO is set" << endl;
    }
    else
    {
        cout << "FE_DIVBYZERO is not set" << endl;
    }

    feclearexcept(FE_ALL_EXCEPT);
    cout << "sqrt(-1) = " << sqrt(-1) << endl;

    if(fetestexcept(FE_INVALID))
    {
        cout << "FE_INVALID is set" << endl;
    }
    else
    {
        cout << "FE_INVALID is not set" << endl;
    }
}

运行该程序时,输出为:

1/0 = inf
FE_DIVBYZERO is set
sqrt(-1) = -nan
FE_INVALID is set