📜  C / C++中的feholdexcept()

📅  最后修改于: 2021-05-30 20:07:58             🧑  作者: Mango

C / C++中的feholdexcept()函数首先将当前浮点环境保存在fenv_t对象中,然后重置所有浮点状态标志的当前值。所述feholdexcept()函数是在C++ cfenv头文件和在用C fenv.h头文件中定义。
句法:

int feholdexcept( fenv_t* envp )

参数:该函数接受单个强制性参数envp ,该参数是指向对象的指针
类型为fenv_t的类型,用于存储浮点环境的当前状态。

返回值:该函数在两个条件下返回int值:

  • 如果函数成功完成,则返回0。
  • 失败时,它将返回一个非零整数。

下面的程序说明了上述函数。

程序1:

// C++ program to illustrate the
// feholdexcept() function
#include 
#pragma STDC FENV_ACCESS on
  
// function to divide
double divide(double x, double y)
{
    // environment variable
    fenv_t envp;
  
    // do the devision
    double ans = x / y;
  
    // use the function feholdexcept
    feholdexcept(&envp);
  
    // clears exception
    feclearexcept(FE_OVERFLOW | FE_DIVBYZERO);
  
    return ans;
}
  
int main()
{
    // It is a combination of all of
    // the possible floating-point exception
    feclearexcept(FE_ALL_EXCEPT);
    double x = 10;
    double y = 0;
  
    // it returns the division of x and y
    printf("x/y = %f\n", divide(x, y));
  
    // the function does not throw
    // any exception on division by 0
    if (!fetestexcept(FE_ALL_EXCEPT)) {
        printf("No exceptions raised");
    }
    return 0;
}
输出:
x/y = inf
No exceptions raised

程式2:

// C++ program to illustrate the
// feholdexcept() function
#include 
#pragma STDC FENV_ACCESS on
using namespace std;
  
// function to print raised exceptions
void raised_exceptions()
{
    cout << "Exceptions raised are : ";
  
    if (fetestexcept(FE_DIVBYZERO))
        cout << " FE_DIVBYZERO\n";
    else if (fetestexcept(FE_INVALID))
        cout << " FE_INVALID\n";
    else if (fetestexcept(FE_OVERFLOW))
        cout << " FE_OVERFLOW\n";
    else if (fetestexcept(FE_UNDERFLOW))
        cout << " FE_UNDERFLOW\n";
    else
        cout << " No exception found\n";
  
    return;
}
  
// Driver code
int main()
{
    // environment variable
    fenv_t envp;
  
    // raise certain exceptions
    feraiseexcept(FE_DIVBYZERO);
    // print the raised exception
    raised_exceptions();
  
    // saves and clears current
    // exceptions by feholexcept function
    feholdexcept(&envp);
    // no exception found
    raised_exceptions();
  
    // restores the previously
    // saved exceptions
    feupdateenv(&envp);
    raised_exceptions();
  
    return 0;
}
输出:
Exceptions raised are :  FE_DIVBYZERO
Exceptions raised are :  No exception found
Exceptions raised are :  FE_DIVBYZERO
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。