C 庫 - feraiseexcept() 函式



C 的fenvferaiseexcept() 函式用於引發“excepts”引數中指定的浮點異常。此引數是浮點異常宏的按位或組合,例如FE_DIVBYZERO、FE_INEXACT、FE_INVALID、FE_OVERFLOW和FE_UNDERFLOW

如果 excepts 在引發異常時包含 FE_OVERFLOW 或 FE_UNDERFLOW,則該函式也可能引發 FE_INEXACT。因為引發異常的順序未指定,但 FE_OVERFLOW 和 FE_UNDERFLOW 始終在 FE_INEXACT 之前引發。

語法

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

int feraiseexcept( int excepts );

引數

此函式接受單個引數:

  • excepts - 它表示要引發的異常標誌的位掩碼。

返回值

如果所有列出的異常都已引發,則此函式返回 0,否則返回非零值。

示例 1

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

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

int main() {
   // Enable exceptions for division by zero and overflow
   if (feraiseexcept(FE_DIVBYZERO | FE_OVERFLOW) != 0) {
      printf("Failed to raise the specified floating-point exceptions.\n");
      return 1;
   } else {
      printf("Successfully raised the specified floating-point exceptions.\n");
   }
   return 0;
}

輸出

以下是輸出:

Successfully raised the specified floating-point exceptions.

示例 2

以下 C 程式使用 feraiseexcept() 函式引發“FE_INEXACT”浮點異常。

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

int main() {
   // Raise the FE_INEXACT floating-point exception
   if (feraiseexcept(FE_INEXACT) != 0) {
      printf("Failed to raise the FE_INEXACT floating-point exception.\n");
      return 1;
   } else {
      printf("Successfully raised the FE_INEXACT floating-point exception.\n");
   }
   return 0;
}

輸出

以下是輸出:

Successfully raised the FE_INEXACT floating-point exception.

示例 3

以下示例引發 FE_OVERFLOW 和 FE_UNDERFLOW 浮點異常。此外,它還檢查並報告已引發的異常,表明當包含 FE_OVERFLOW 或 FE_UNDERFLOW 時,也可能引發 FE_INEXACT。

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

int main() {
   // Raise the FE_OVERFLOW and FE_UNDERFLOW floating-point exceptions
   if (feraiseexcept(FE_OVERFLOW | FE_UNDERFLOW) != 0) {
      printf("Failed to raise the specified floating-point exceptions.\n");
      return 1;
   } else {
      printf("Successfully raised the specified floating-point exceptions.\n");
   }

   // Check which exceptions are currently raised
   int raised_excepts = fetestexcept(FE_ALL_EXCEPT);
   if (raised_excepts & FE_OVERFLOW) {
      printf("FE_OVERFLOW is raised.\n");
   }
   if (raised_excepts & FE_UNDERFLOW) {
      printf("FE_UNDERFLOW is raised.\n");
   }
   if (raised_excepts & FE_INEXACT) {
      printf("FE_INEXACT is also raised.\n");
   }
   return 0;
}

輸出

以下是輸出:

Successfully raised the specified floating-point exceptions.
FE_OVERFLOW is raised.
FE_UNDERFLOW is raised.
c_library_fenv_h.htm
廣告

© . All rights reserved.