数值的整数次方*

bool g_bInvalidInput = false;
double power(double base, int exponent)
{
	if (equal(base, 0.0) && exponent < 0)
	{
		g_bInvalidInput = true;
		return 0.0;
	}

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

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

bool equal(double value1, double value2)
{
	if ((value1 - value2 > -0.0000001) &&
		(value1 - value2 < 0.0000001))
		return true;
	else
		return false;
}

double PowerWithUnsignedInt(double base, unsigned int absExponent)
{
	if (absExponent == 0)
		return 1;
	if (absExponent == 1)
		return base;

	double result = PowerWithUnsignedInt(base, absExponent >> 1);
	result *= result;
	if (absExponent & 0x1 == 1)
		result *= base;
	return result;
}

  

posted on 2021-02-07 17:45  Noora&w  阅读(41)  评论(0编辑  收藏  举报