标签:
11. 数值的整数次方
1 #include <iostream> 2 3 int error = 0; 4 double Power(double base, int exponent); 5 6 int main(int argc, char *argv[]) { 7 double base; 8 int exponent; 9 std::cin >> base >> exponent; 10 11 double result = Power(base, exponent); 12 13 std::cout << error << std::endl; 14 std::cout << result << std::endl; 15 } 16 17 double Power(double base, int exponent) { 18 if(0 == exponent) 19 return 0; 20 if(exponent > 0) { // 指数为正 21 if(1 == exponent) 22 return base; 23 if(exponent % 2 == 0) { // 偶数 24 double tmp = Power(base, exponent/2); 25 return tmp*tmp; 26 } else { // 奇数 27 double tmp = Power(base, (exponent-1)/2); 28 return tmp*tmp*base; 29 } 30 } else { // 指数为负 31 if(base == 0) { 32 error = -1; 33 return 0; 34 } 35 if(-1 == exponent) 36 return 1/base; 37 if(exponent % 2 == 0) { // 偶数 38 double tmp = Power(base , exponent/2); 39 return tmp*tmp; 40 } else { // 奇数 41 double tmp = Power(base , (exponent+1)/2); 42 return tmp*tmp*(1/base); 43 } 44 } 45 }
*book:
1 #include <iostream> 2 3 bool error = false; 4 double Power(double base, int exponent); 5 double PositivePower(double base, unsigned int exponent); 6 bool equal(double m, double n); 7 8 int main(int argc, char *argv[]) { 9 double base; 10 int exponent; 11 std::cin >> base >> exponent; 12 13 double result = Power(base, exponent); 14 15 std::cout << error << std::endl; 16 std::cout << result << std::endl; 17 } 18 19 double Power(double base, int exponent) { 20 // 底数为0, 指数为负数/0/正数 21 if(equal(base, 0.0)) { 22 if(exponent < 0) { 23 error = true; 24 return 0; 25 } else 26 return 0; 27 } 28 29 //指数为正数/0 30 unsigned int absexponent = (unsigned int) exponent; 31 if(exponent < 0) { 32 absexponent = (unsigned int)(-exponent); 33 } 34 double result = PositivePower(base, absexponent); 35 return (exponent < 0) ? 1/result : result; 36 } 37 38 bool equal(double m, double n) { 39 if(m-n < 0.0000001 && m-n > -0.0000001) 40 return true; 41 return false; 42 } 43 44 double PositivePower(double base, unsigned int exponent) { 45 if(exponent == 1) 46 return base; 47 if(exponent == 0) 48 return 0; 49 double result = PositivePower(base, exponent >> 1); 50 result *= result; 51 if(exponent & 0x1 == 1) // 奇数 52 result *= base; 53 return result; 54 }
思路:利用乘方的性质
本题看似简单,但完美的写出程序需要思考全面:
1)底数/指数分别为0,负数,正数的情形;(a的n次幂是a的-n次幂的倒数,利用此点可简化程序)
2)底数判断是否为0的方法(double base== 0错误);
标签:
原文地址:http://www.cnblogs.com/tanfy/p/5553947.html