_matherr

處理數學錯誤。

語法

int _matherr(struct _exception *except);

參數

except
包含錯誤資訊之結構的指標。

傳回值

_matherr 會傳回 0 表示錯誤,或表示成功的非零值:

  • 如果 _matherr 傳回 0,可以顯示錯誤訊息,並 errno 設定為適當的錯誤值。
  • 如果 _matherr 傳回非零值,則不會顯示任何錯誤訊息,且 errno 保持不變。

如需傳回碼的詳細資訊,請參閱 errno_doserrno_sys_errlist_sys_nerr

備註

函式會 _matherr 處理數學程式庫浮點函式所產生的錯誤。 偵測到錯誤時,這些函式會呼叫 _matherr 。 此互動不會受到 編譯 程式或浮點控制字 浮點模式影響。 因為 _matherr 是程式庫函式,所以數學 內建函式 不會呼叫它。

針對特殊錯誤處理,您可以提供 不同的定義 _matherr 。 如果您使用 C 執行時間程式庫的動態連結版本 (CRT),您可以將用戶端可執行檔中的預設 _matherr 常式取代為使用者定義的版本。 不過,您無法在 CRT DLL 的 DLL 用戶端中取代預設 _matherr 常式。

在數學常式中發生錯誤時, _matherr 會以型別結構的指標 _exception 來呼叫 , <math.h> 做為引數。 結構 _exception 包含下列元素。

struct _exception
{
    int    type;   // exception type - see below
    char*  name;   // name of function where error occurred
    double arg1;   // first argument to function
    double arg2;   // second argument (if any) to function
    double retval; // value to be returned by function
};

成員 type 會指定數學錯誤的類型。 這是 中 <math.h> 定義的下列其中一個值:

Macro 描述
_DOMAIN 引數網域錯誤
_SING 引數單數
_OVERFLOW 溢位範圍錯誤
_PLOSS 部分遺失重要性
_TLOSS 重大損失總計
_UNDERFLOW 結果太小,無法表示 (目前不支援此條件。

結構成員 name 是 Null 終止字串的指標,其中包含造成錯誤的函式名稱。 結構成員 arg1 ,並 arg2 指定造成錯誤的值。 如果只指定一個引數,則會儲存在 中 arg1

指定錯誤 retval 的預設傳回值為 。 如果您變更傳回值,它必須指定是否確實發生錯誤。

需求

常式 必要的標頭
_matherr <math.h>

如需相容性詳細資訊,請參閱相容性

範例

/* crt_matherr.c
* Illustrates writing an error routine for math
* functions. 
* The error handling function must be named _matherr
*/

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

int main()
{
    /* Do several math operations that cause errors. The _matherr
     * routine handles _DOMAIN errors, but lets the system handle
     * other errors normally.
     */
    printf( "log( -2.0 ) = %e\n", log( -2.0 ) );
    printf( "log10( -5.0 ) = %e\n", log10( -5.0 ) );
    printf( "log( 0.0 ) = %e\n", log( 0.0 ) );
}

/* Handle several math errors caused by passing a negative argument
* to log or log10 (_DOMAIN errors). When this happens, _matherr
* returns the natural or base-10 logarithm of the absolute value
* of the argument and suppresses the usual error message.
*/
int _matherr(struct _exception *except)
{
    /* Handle _DOMAIN errors for log or log10. */
    if (except->type == _DOMAIN)
    {
        if (strcmp(except->name, "log") == 0)
        {
            except->retval = log(-(except->arg1));
            printf("Special: using absolute value: %s: _DOMAIN "
                     "error\n", except->name);
            return 1;
        }
        else if (strcmp(except->name, "log10") == 0)
        {
            except->retval = log10(-(except->arg1));
            printf("Special: using absolute value: %s: _DOMAIN "
                     "error\n", except->name);
            return 1;
        }
    }
    printf("Normal: ");
    return 0;    /* Else use the default actions */
}
Special: using absolute value: log: _DOMAIN error
log( -2.0 ) = 6.931472e-01
Special: using absolute value: log10: _DOMAIN error
log10( -5.0 ) = 6.989700e-01
Normal: log( 0.0 ) = -inf

另請參閱

數學和浮點支援