题目描述:实现函数double Power(double base,int exponent),求base 的exponent次方。不得使用库函数,同时不需要考虑大数问题。
分析,题目要求实现库函数pow(),由于不需要考虑大数问题,不必担心溢出,那么就需要对输入的各种情况进行分类处理。当输入base == 0 或 base == 1时它们的任意次方都等于其本身;当输入exponent < 0 时, = ;当exponent == 0时, = 1; 然后可以用快速幂求整数的次方。
代码:
bool g_InvalidInput = false; //全局变量,用来指示是否发生错误或异常bool Equal(double a,double b){ //浮点数比较大小if(std::fabs(a - b) < 0.000001)return true;else return false;
}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; //如果exponent小于0,就取它的倒数return result;
}double PowerWithUnsignedExponent(double,unsigned exponent){ //快速幂if(base == 0)return 0;if(exponent == 0 || base == 1)return 1;if(exponent == 1)return base;double result = PowerWithUnsignedExponent(base,exponent >> 1); //先求出base的(1/2 exponent)次方result *= result; //然后再平方求得base的exponent次方if(exponent & 0x1 == 1){result *= base; //如果exponent是奇数就再乘以一个base}return result;
}