C 庫 - feclearexcept() 函式



C 的fenvfeclearexcept()函式用於清除由位掩碼引數excepts指定的浮點環境中的浮點異常。如果except等於'0',則返回0。

位掩碼引數excepts是浮點異常宏(如FE_DIVBYZERO、FE_INEXACT、FE_INVALID、FE_OVERFLOW、FE_UNDERFLOW和FE_ALL_EXCEPT)的按位或組合。

語法

以下是feclearexcept()函式的C庫語法:

int feclearexcept(int excepts);

引數

此函式接受一個引數:

  • excepts - 它表示要清除的異常標誌的位掩碼列表。

返回值

如果所有異常都已清除,則此函式返回'0'。否則,如果發生錯誤,則返回非零值。

示例 1

以下是用C編寫的基本程式,用於演示feclearexcept()函式的使用。

#include <stdio.h>
#include <math.h>
#include <fenv.h>

int main() {
   // Clear all floating-point exceptions.
   feclearexcept(FE_ALL_EXCEPT);
   
   // floating-point operation.
   double result = sqrt(-1.0);
   printf("%lf \n", result);
   
   // If floating-point exceptions were raised.
   if (fetestexcept(FE_INVALID)) {
     // Handle the invalid operation exception.
     printf("Invalid floating-point operation occurred.\n");
   }
   else {
       printf("No Invalid floating-point operation occurred. \n");
   }
   return 0;
}

輸出

如果浮點數無效,我們將得到以下輸出:

-nan 
Invalid floating-point operation occurred.

示例 2

傳遞excepts值為0

在以下示例中,如果我們傳遞except值為0,則feclearexcept()函式返回0。

#include <stdio.h>
#include <math.h>
#include <fenv.h>

int main() {
   // Clear all floating-point exceptions.
   feclearexcept(FE_ALL_EXCEPT);
   int excepts = 0;
   int res = feclearexcept(excepts);
   printf("%d", res);
}

輸出

以下是輸出:

0

示例 3

下面的程式執行浮點除法運算,如果我們嘗試除以0,則會引發除以零異常。

#include <stdio.h>
#include <fenv.h>

int main() {
   // Clear following floating-point exceptions.
   feclearexcept(FE_DIVBYZERO | FE_OVERFLOW);

   //divide-by-zero exception.
   double result = 1.0 / 0.0;

   // Check if the divide-by-zero exception was raised.
   if (fetestexcept(FE_DIVBYZERO)) {
      printf("Divide-by-zero exception.\n");
   } else {
      printf("No divide-by-zero exception.\n");
   }

   // Check if the overflow exception was raised.
   if (fetestexcept(FE_OVERFLOW)) {
      printf("Overflow exception.\n");
   } else {
      printf("No overflow exception.\n");
   }

   return 0;
}

輸出

以下是輸出:

Divide-by-zero exception.
No overflow exception.
c_library_fenv_h.htm
廣告

© . All rights reserved.