捕获数学函数异常,捕获数学函数异常
【 tulaoshi.com - C语言心得技巧 】
捕获数学函数异常
作者: 江汉石油学院计算机系 周云才
下载本文配套源代码
假如我们要用一个数学函数,比如反正弦函数asin(x),如果变元x的值是由用户提供或某个中间结果,则在调用时必须判断其取值范围是合理,是否满|x|<=1?即
if(fabs(x)<=1)对数函数也可作类似的处理。但是如果遇到幂函数pow(x,y)时,问题就不那么简单了。仔细分析将发现:
y=asin(x);
else
y=…
int _matherr( struct _exception *except );为了利用此函数,只需在应用数学函数的地方定义一个这样的函数,例如
#include <math.h>#include <stdio.h>void main(){double x,y,z;x=-1.23;y=-1;z=pow(x,y);printf("%gn",z);y=-1.1;z=pow(x,y);printf("%gn",z);}int _matherr(struct _exception *except){char* errorString[] = {"_DOMAIN","_SING", "_OVERFLOW", "_PLOSS", "_TLOSS", "_UNDERFLOW"};printf("Error function name is %sn",except->name);printf("The varianbles arg1=%g,arg2=%gn",except->arg1,except->arg2);printf("The error type = %sn",errorString[except->type]);printf("The error value=%gn",except->retval);except->retval=1234;printf("After handling error value=%gn",except->retval);return 1;}编译、运行,结果为 -0.813008
来源:http://www.tulaoshi.com/n/20160129/1485488.html
如果您有什么好的建议或者疑问,可以联系我们。 商务合作QQ:3272218541;3282258740。商务合作微信:13319608704;13319603564。
加好友请备注机构名称。让我们一起学习、一起进步tulaoshi.com 版权所有 © 2019 All Rights Reserved. 湘ICP备19009391号-3
微信公众号