Description:
Implement the double power (double base, int exponent) function to calculate the power of base's exponent. Do not use library functions, and do not need to consider large numbers.
Analysis description:
The first thing to do to implement a function is to fully consider all the possibilities of its parameters. For the numeric functions in this question, you should consider the integer, 0, negative number, floating point type, integer type, and whether it is a large number.
If exponent is a negative number, the base cannot be 0 in the power function. Otherwise, there will be a problem of division by 0. For this error, you can specify a flag. If exponent is a negative number, calculate the reciprocal of the power of base (-exponent. In addition, if base is 0.0 and exponent is 0, it makes no sense,
Int flag = 0; // flag. If both base and exponent are 0, set the double power (double base, int exponent) {If (equal (base, 0.0) & exponent <0) {/* Here we cannot simply use base = 0.0 to compare */flag = 1; return 0.0;} unsigned int absexponent = (unsigned INT) exponent; if (exponent <0) absexponent = (unsigned INT) (-exponent);/* If exponent is less than zero, evaluate its absolute value */double result = powerwithunsignedexponent (base, absexponent ); if (exponent <0) Result = 1.0/result; return result;} double powerwithunsignedexponent (double base, unsigned int absexponent) {double result = 1.0; int I; for (I = 1; I <= absexponent; ++ I) Result * = base; return result;} int equal (double num1, double num2) {If (num1-num2>-0.0000001)/* compare the two floating point numbers for the same method */& (num1-num2) <0.0000001) return 1;
Although the above method can solve the problem, it is not efficient. If exponent is large, you can use another method to solve it:
double PowerWithUnsignedExponent(double base, unsigned int absexponent){if(absexponent == 0)return 1;if(absexponent == 1)return base;double result = PowerWithUnsignedExponent(base, absexponent >> 1);result * = result;if(absexponent & 0x1 == 1)result *= base;return result;}
Summary: The first program in the above section used a method to handle errors: The global variable method. There are two other processing methods: Return Value Method and Exception Processing Method.