Prove safety integer power value offer- face questions 16- - Digital

/ * 
Title: 
	implement function double Power (double base, int exponent ), 
	seeking base of the exponent power. 
* / 
/ * 
Thinking: 
	the case that the need to consider more: 
		negative power of 1,0 error. 
		2, double the value of 0 is determined, the accuracy required. 
		3, consider the exponent is a negative number. 
	'S innovative point: 
		find x (n-th power), the available x (n / 2-th power) * 2 (n / 2-th power) x is even 
		find x (n-th power), the available x (n / 2-th power ) * 2 (n / 2-th power) * xx is an odd number 
* / 
#include <the iostream> 
#include <string.h> 
#include <algorithm> 
#include <the cmath> 
the using namespace STD; 
#define MIN_VALUE-1E. 8 

BOOL g_InvalidInput to false =; 

BOOL equal0 (Double num1) { 
    IF (ABS (num1) <MIN_VALUE) return to true; 
    return to false; 
}
PowerWithUnsignedExponent Double (Double Base, exponent The unsigned int) { 
    IF (exponent The == 0) { 
        return. 1; 
    } 
    IF (exponent The ==. 1) { 
        return Base; 
    } 
	// bit operation instead of division by 
    double result = PowerWithUnsignedExponent (base, exponent . 1 >>); 
    Result = Result *; 
	// the exponent is an odd number is determined, by a need more. 
	// bit operations instead of using modulo 
    IF (exponent The == & 0x1. 1) { 
        Result * Base =; 
    } 
    return Result; 
} 

Double the Power (Double Base, exponent The int) { 
    IF (equal0 (Base) && exponent The <0) { 
        g_InvalidInput to true =; 
        return 0.0;  
    }
    unsigned int absExponent = (unsigned int) (exponent The);
    if(exponent < 0){
        absExponent = (unsigned int)(-exponent);
    }
    double result = PowerWithUnsignedExponent(base,absExponent);
    if(exponent < 0){
        result = 1.0 / result;
    }
    return result;
}


int main(){
    cout<<Power(2,9)<<endl;

}

   

Guess you like

Origin www.cnblogs.com/buaaZhhx/p/11861147.html