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


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


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 <bits/stdc++.h> 
#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 <bits/stdc++.h> 
#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


相关用法


注:本文由纯净天空筛选整理自Aman Goyal 2大神的英文原创作品 feholdexcept() in C/C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。