需要考虑 的情况
1、0的0次方
2、0的负数次方
3、效率问题
bool isEqual(double num1,double num2)
{
if((num1-num2>-0.00001)&&(num1-num2<0.00001))return true;
else return false;
}
double withUnsignedExp(double base,unsigned int exp)
{
if(exp==0) return 1;
else if(exp==1) return base;
double result = 1;
while(exp)
{
if(exp&1) result = result * base;
exp=exp>>1;
base = base * base;
}
return result;
}
int invalid = false;
double power(double base,int exp)
{
if(isEqual(base,0.0) && exp<0)
{
invalid = false;
return 0.0;
}
unsigned int us_exp = (unsigned int)(exp);
if(exp<0) us_exp = (unsigned int)(-exp);
double result = withUnsignedExp(base,us_exp);
if(exp<0) result = 1.0/result;
return result;
}
某个数的正数n次方递归写法
double withUnsignedExp1(double base,unsigned int exp)
{
if(exp==0) return 1;
else if(exp==1) return base;
double result = withUnsignedExp1(base,exp>>1);
result = result*result;
if(exp%2==1) result*=base;
return result;
}