oral_quiz->#实现类似库中的pow#

#include <stdio.h>
#include <exception>

bool g_InvalidInput = false;

bool equal(double num1, double num2) {
	return (num1 - num2 > -0.00000001 && num1 - num2 < 0.00000001) ? true : false;
}

double PowerWithUnsignedExponent(double base, unsigned int exponent) {
	double result = 1.0;
	for(unsigned int i = 1; i <= exponent; ++i)
		result *= base;
	return result;
}

//太渣
double NewPowerWithUnsignedExponent(double base, unsigned int exponent) {
	if(exponent == 0) return 1;
	if(exponent == 1) return base;

	if(exponent % 2) {
		double half = NewPowerWithUnsignedExponent(base, (exponent-1)/2);
		return half*half*base;
	}
	else {
		double half = NewPowerWithUnsignedExponent(base, exponent/2);
		return half*half;
	}
}

//hht's advanced PowerWithUnsignedExponent
double hhtPowerWithUnsignedExponent(double base, unsigned int exponent) {
	if(exponent == 0) return 1;
	if(exponent == 1) return base;

	double result = hhtPowerWithUnsignedExponent(base, exponent >> 1);
	result *= result;
	if((exponent & 0x1) == 1) result *= base;	//exponent & 0x1不加括弧对,但编译器warning

	return result;
}

double Power(double base, int exponent) {
	g_InvalidInput = false;

	if(equal(base, 0.0) && exponent < 0) {
		g_InvalidInput = true;
		return 0.0;
	}

	unsigned int absExponent = (unsigned int)exponent;
	if(exponent < 0)
		absExponent = (unsigned int)(-exponent);

	double result = hhtPowerWithUnsignedExponent(base, absExponent);
	if(exponent < 0) return 1.0/result;

	return result;
}

double MyPower(double base, int exponent) {
	//exponent == 0
	if(!exponent) return 1.0;

	int flag = exponent < 0 ? -1 : 1;
	exponent = exponent < 0 ? exponent*(-1) : exponent;
	while(--exponent) {
		base *= base;
	}
	return flag < 0 ? 1.0/base : base;
}

void Test(double base, int exponent, double expected) {
	printf("Test for %lf ", base);
	if(equal(expected, Power(base, exponent)))
		printf("passed.\n");
	else
		printf("failed.\n");
}

int main(int argc, char* argv[]) {
	Test(2.0, 2, 4.0);
	Test(5.5, 0, 1.0);
	Test(3.0, -2, 1.0/9);
	return 0;
}



你可能感兴趣的:(pow)