The integer power of a value.
Question: implement the function double Power (double base, int exponent) to calculate the Power of base's exponent. Do not use library functions, and do not need to consider large numbers.
Note the following points for this question:
Based on the above four points of attention, we can write the exponential program, the Code is as follows:
1 # include <iostream> 2 # include <stdlib. h> 3 using namespace std; 4 5 // global variable. Check it during testing to determine whether the input is correct. 6 bool g_InvalidInput = false; 7 8 // due to precision, variables of the double type cannot use equal signs to determine whether two numbers are equal. Therefore, you need to write the equsl function 9 bool equal (double num1, double num2) 10 {11 if (num1-num2)> -0.0000001 & (num1-num2) <0.0000001) 12 return true; 13 else14 return false; 15} 16 17 // method 1 uses loop 18 double PowerWithUnsignedExponent (double base, unsigned int ex Ponent) 19 {20 double result = 1.0; 21 for (int I = 1; I <= exponent; ++ I) 22 result * = base; 23 24 return result; 25} 26 27 // method 2 uses recursion 28 double PowerWithUnsignedExponent1 (double base, unsigned int exponent) 29 {30 if (exponent = 0) 31 return 1; 32 if (exponent = 1) 33 return base; 34 35 // bitwise operation instead of dividing by 2, bit operations are much more efficient than multiplication, division, and remainder operations. 36 double result = PowerWithUnsignedExponent1 (base, exponent> 1); 37 result * = result; 38 39 if (exponent & 0x1 = 1) // bitwise AND, instead of the remainder %, determine whether a number is an odd or even number 40 result * = base; 41 42 return result; 43} 44 45 double Power (double base, int exponent) 46 {47 g_InvalidInput = false; 48 49 // if the base number is 0 and the index is smaller than 0, the input is invalid. 50 if (equal (base, 0.0) & exponent <0) 51 {52 g_InvalidInput = true; // at this time, the global variable becomes true 53 cout <"invalid input" <ends; 54 return 0.0; 55} 56 57 // judge whether the exponent is positive or negative, obtain the absolute value of the exponent 58 unsigned int absExponent = (unsigned int) exponent; 59 if (exponent <0) 60 absExponent = (unsigned int) (-exponent ); 61 62 // use method 2 here. Use method 1 to change the code. 63 double result = PowerWithUnsignedExponent1 (base, absExponent); 64 65 // if the index is smaller than 0, take the last 66 if (exponent <0) 67 result = 1.0/result; 68 69 return result; 70} 71 int main () 72 {73 double num1 = Power (2.0,-2); // 0.2574 double num2 = Power (2.0, 2 ); // 475 double num3 = Power (0.0, 2); // 076 double num4 = Power (0.0, 0); // meaningless, select output 1 77 78 cout <num1 <endl; 79 cout <num2 <endl; 80 cout <num3 <endl; 81 cout <num4 <endl; 82 83 cout <endl; 84 85 // invalid input returns 0 86 double num5 = Power (0,-2 ); 87 cout <num5 <endl; 88 89 return 0; 90}