bool g_InvalidInput = false; //定義全局變量來標識是否出錯
double PowerWithunsignedExponent(double base,unsigned int exponent){
if(exponent ==0)
return 1;
if(exponent==1)
return base;
double result = PowerWithunsignedExponent(base,exponent>>1); // 細節,用移位操做來代替除以二it
result*=result;
if(exponent&0x1==1)用位與運算符代替求餘
result*=base;
return result;
}
bool equal(double num1, double num2)
{
if ((num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001))
return true;
else
return false;
}
double Power(double base,int exponent){
g_InvalidInput = false;
if(equal(base,0.0)&&exponent<0){ //細節,double類型數據的判斷是否相等
g_InvalidInput = true;
return 0.0;
}
unsigned int absExponent = (unsigned int)(exponent);//取expnent的絕對值
if(exponent<0){
absExponent = (unsigned int)(-exponent);
}
double result = PowerWithunsignedExponent(base,absExponent);
if(exponent<0)
result = 1.0/result;//取倒數
return result;
}變量