名稱空間
變體
操作

MATH_ERRNO, MATH_ERREXCEPT, math_errhandling

來自 cppreference.com
< cpp‎ | 數值‎ | 數學
 
 
 
常用數學函式
函式
基本操作
(C++11)  
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)(C++11)(C++11)
指數函式
(C++11)
(C++11)

(C++11)
(C++11)
冪函式
(C++11)
(C++11)
三角
雙曲函式
(C++11)
(C++11)
(C++11)

誤差函式和伽馬函式
(C++11)
(C++11)
(C++11)
(C++11)
取整浮點運算
(C++11)(C++11)(C++11)
(C++11)
(C++11)
(C++11)(C++11)(C++11)
浮點操縱函式
(C++11)(C++11)
(C++11)
(C++11)
(C++11)(C++11)
(C++11)
分類和比較
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
型別
(C++11)
(C++11)
(C++11)
宏常量
math_errhandlingMATH_ERRNOMATH_ERREXCEPT
(C++11)  
(C++11)
(C++11)
分類
(C++11)(C++11)(C++11)(C++11)(C++11)


 
定義於標頭檔案 <cmath>
#define MATH_ERRNO        1
(C++11 起)
#define MATH_ERREXCEPT    2
(C++11 起)
#define math_errhandling  /*實現定義*/
(C++11 起)

宏常量 math_errhandling 展開為一個 int 型別的表示式,它或者等於 MATH_ERRNO,或者等於 MATH_ERREXCEPT,或者等於它們的按位或 (MATH_ERRNO | MATH_ERREXCEPT)。

math_errhandling 的值表示浮點運算子和函式執行的錯誤處理型別。

常量 解釋
MATH_ERREXCEPT 指示使用浮點異常:至少 FE_DIVBYZEROFE_INVALIDFE_OVERFLOW<cfenv> 中定義。
MATH_ERRNO 指示浮點操作使用變數 errno 報告錯誤。

如果實現支援 IEEE 浮點算術 (IEC 60559),則要求 math_errhandling & MATH_ERREXCEPT 為非零。

識別以下浮點錯誤條件:

條件 解釋 errno 浮點異常 示例
域錯誤 引數超出了操作在數學上定義的範圍(每個函式的描述都列出了所需的域錯誤)。 EDOM FE_INVALID std::acos(2)
極點錯誤 函式的數學結果恰好是無窮大或未定義。 ERANGE FE_DIVBYZERO std::log(0.0), 1.0 / 0.0
因溢位導致的範圍錯誤 數學結果是有限的,但在四捨五入後變為無窮大,或者在向下舍入後變為最大的可表示有限值。 ERANGE FE_OVERFLOW std::pow(DBL_MAX, 2)
因下溢導致的範圍錯誤 結果是非零的,但在四捨五入後變為零,或者在損失精度後變為次正規數。 ERANGE 或不變(實現定義) FE_UNDERFLOW 或無(實現定義) DBL_TRUE_MIN / 2
不精確結果 結果必須經過四捨五入才能適應目標型別。 不變 FE_INEXACT 或無(未指定) std::sqrt(2), 1.0 / 10.0

[編輯] 注意

數學庫函式是否引發 FE_INEXACT 通常未指定,但可能在函式描述中明確指定(例如 std::rint 對比 std::nearbyint)。

在 C++11 之前,未指定浮點異常;任何域錯誤都要求 EDOM,溢位要求 ERANGE,下溢則由實現定義。

[編輯] 示例

#include <cerrno>
#include <cfenv>
#include <cmath>
#include <cstring>
#include <iostream>
// #pragma STDC FENV_ACCESS ON
 
int main()
{
    std::cout << "MATH_ERRNO is "
              << (math_errhandling & MATH_ERRNO ? "set" : "not set") << '\n'
              << "MATH_ERREXCEPT is "
              << (math_errhandling & MATH_ERREXCEPT ? "set" : "not set") << '\n';
    std::feclearexcept(FE_ALL_EXCEPT);
    errno = 0;
    std::cout <<  "log(0) = " << std::log(0) << '\n';
    if (errno == ERANGE)
        std::cout << "errno = ERANGE (" << std::strerror(errno) << ")\n";
    if (std::fetestexcept(FE_DIVBYZERO))
        std::cout << "FE_DIVBYZERO (pole error) reported\n";
}

可能的輸出

MATH_ERRNO is set
MATH_ERREXCEPT is set
log(0) = -inf
errno = ERANGE (Numerical result out of range)
FE_DIVBYZERO (pole error) reported

[編輯] 參閱

浮點異常
(宏常量) [編輯]
擴充套件為 POSIX 相容的執行緒區域性錯誤碼變數的宏
(宏變數)[編輯]
C 文件 關於 math_errhandling