标签:
题目描述:5.00e-01f
注意:
1.当指数是负数的时候,可以先对指数求绝对值,然后算出次方的结果之后求倒数。
2.当底数是0,指数是负数的时候应做特殊处理。
3.判断两个浮点数是否相等不应该直接用==。
#include<cstdio> #include<cstring> #include<cstdlib> bool g_InvalidInput = false; bool equal(double num1,double num2) { if((num1 - num2 >= -0.0000001) && (num1 - num2 <= 0.0000001)) { return true; } return false; } double PowerWithUnsignedExponent(double base,unsigned int exponent) { if(exponent == 0) return 1; if(exponent == 1) return base; double result = PowerWithUnsignedExponent(base,exponent>>1); result *= result; if(exponent & 0x1 == 1) result *= base; return result; } double Power(double base,int exponent) { g_InvalidInput = false; if(equal(base,0.0) && exponent < 0) { g_InvalidInput = true; return 0.0; } unsigned int absExponent = (unsigned int)exponent; if(exponent < 0) absExponent = (unsigned int)(-exponent); double result = PowerWithUnsignedExponent(base,absExponent); if(exponent < 0) result = 1.0 / result; return result; } int main() { int n; scanf("%d",&n); double base; int exponent; while(n--) { scanf("%lf%d",&base,&exponent); double result = Power(base,exponent); if(g_InvalidInput) printf("INF\n"); else { printf("%.2ef\n",result); } } return 0; }
标签:
原文地址:http://blog.csdn.net/biluyang/article/details/44058079