思路:
方法一:指数exponent为负,需要把exponent变为正数,然后再对base^(-exponent)取倒数;当exponent为负数时,还需考虑base为0的情况;double和0相等的判断。
double Power(double base,int exponent){
double result=0.0;
if(equal(0.0,base)&&exponent<0)
return -0.1;
if(exponent<0)
result= PowerWithPosExponent(base,-exponent);
result=1/result;
if(exponent>=0)
result= PowerWithPosExponent(base,exponent);
}
double PowerWithPosExponent(double base,int exponent){
double result=1.0;
for(int i=1;i<=exponent;i++){
result*=base;
}
}
boolean equal(double num1,double num2){
if(num1-num2>-0.000001&&num1-num2<0.000001)
return true;
return false;
}
方法二:递归
double Power(double base,int exponent){
if(exponent==0)
return 1;
if(exponent==1)
return base;
double result=Power(base,exponent>>1)
result*=result;
if(base&0x1==1)
result*=base;
return result;
}