当前位置: 首页 > 图文教程 > 开发语言 > VC++ > 捕获数学函数异常
捕获数学函数异常 下载本文配套源代码 if(fabs(x)<=1)对数函数也可作类似的处理。但是如果遇到幂函数pow(x,y)时,问题就不那么简单了。仔细分析将发现:
例如:pow(-1.2,-1.2)=-1.#IND。如果要编程处理,至少需要六个if语句。即使如此,也有麻烦:如何判断一个double型的变元的值是整数还是小数? 为了处理数学函数运算中出现的异常,VC++提供了一个函数_mather,其原型在<math.h>中: 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("%g\n",z); y=-1.1; z=pow(x,y); printf("%g\n",z);}int _matherr(struct _exception *except){char* errorString[] = {"_DOMAIN","_SING", "_OVERFLOW", "_PLOSS", "_TLOSS", "_UNDERFLOW"}; printf("Error function name is %s\n",except->name); printf("The varianbles arg1=%g,arg2=%g\n",except->arg1,except->arg2); printf("The error type = %s\n",errorString[except->type]); printf("The error value=%g\n",except->retval); except->retval=1234; printf("After handling error value=%g\n",except->retval); return 1;} 编译、运行,结果为
|