捕获数学函数异常
2010-01-23 20:32:27 来源:WEB开发网注意:数学函数的错误类型定义如下:
_DOMAIN 变元定义域错误;
_SING 变元奇异点错误;
_OVERFLOW 溢出错误;
_PLOSS 精度部分遗失;
_TLOSS 精度丢失;
_UNDERFLOW 下溢错误,结果太小,无发表示。
下面是MSDN给我们提供的一个示例供大家参考:
/* MATHERR.C illustrates writing an error routine for math
* functions. The error function must be:
* _matherr
*/
#include <math.h>
#include <string.h>
#include <stdio.h>
void 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
", log( -2.0 ) );
printf( "log10( -5.0 ) = %e
", log10( -5.0 ) );
printf( "log( 0.0 ) = %e
", 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
", except->name );
return 1;
}
else if( strcmp( except->name, "log10" ) == 0 )
{
except->retval = log10( -(except->arg1) );
printf( "Special: using absolute value: %s: _DOMAIN "
"error
", except->name );
return 1;
}
}
else
{
printf( "Normal: " );
return 0; /* Else use the default actions */
}
}
输出结果
Special: using absolute value: log: _DOMAIN error
log( -2.0 ) = 6.931472e-001
Special: using absolute value: log10: _DOMAIN error
log10( -5.0 ) = 6.989700e-001
Normal: log( 0.0 ) = -1.#INF00e+000
本文配套源码
更多精彩
赞助商链接