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


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