The question comes from offoffoffoffer. Description:
Implement the function Double POW (double base, unsigned exponent)
Here are a few notes:
1. exponent may be positive or negative.
2. When base is 0 and exponent is negative, the result is not defined in mathematics.
3. Use of mathematical formulas:
A ^ (n/2) * A ^ (n/2) N is an even number.
A ^ n = a ^ (n-1)/2) * A ^ (n-1)/2) * a n is an odd number
The Code is as follows:
# Include <iostream> # include <cstdio> using namespace STD; bool valid_input = false; // determine whether the input is valid bool equal (double num1, double num2) based on this value) // determine whether two values are equal {If (num1-num2>-1e-6 & num1-num2 <1e-6) return true; return false ;} /// // a ^ (n/2) * A ^ (n/2) N is an even number // a ^ n = // a ^ (n/2) * A ^ (n/2) * a n is an odd number // double pow_with_unsigned (double base, unsigned int exponent) {If (exponent = 0) // The 0 power of any number is 1 return 1; if (exponent = 1) return base; double result = pow_with_unsigned (base, exponent> 1); Result * = result; If (exponent & 0x01 = 1) // returns an odd number of results * = base; return result;} double POW (double base, int exponent) {valid_input = false; If (equal (base, 0.0) & exponent <0) // when the base number is 0, when its power is a negative number, the specified input is invalid, and it returns 0 (1 can also be used, indicating that the input is incorrect) {valid_input = true; return 0.0; // The base number is 0, returns 0.0 if the index is less than 0, and indicates that the input is invalid} unsigned int abs_exponent = (unsigned INT) exponent; If (exponent <0) abs_exponent = (unsigned INT) (-exponent ); double result = pow_with_unsigned (base, abs_exponent); If (exponent <0) // If the index is smaller than 0, the reciprocal result of the result is 1.0/result; return result ;} int main (void) {double rel = POW (0,-3); cout <rel <Endl; return 0 ;}