# 数值的整数次方

double Power(double base,int exponent)

{

double result=1.0;

for(int i=1;i<=exponent;++i)

result*=base;

return result;

}

bool q_InvalidInput = false;
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 = PowerWithUnsignedExponent(base,absExponent);
if (exponent < 0)
result = 1.0 / result;
return result;
}
double PowerWithUnsignedExponent(double base, unsigned int exponent)
{
double result = 1.0;
for (int i = 1; i <= exponent; ++i)
result *= base;
return result;
}
bool equal(double num1, double num2)
{
if ((num1 - num2 > -0.0000001) && (num1 - num2) < 0.0000001))
return true;
else
return false;
}

使用公式求a的n次方：

double PowerWithUnsignedExponent(double base, unsigned int exponent)
{
if (exponent == 0)
return 1;
if (exponent == 1)
return base;
double result = PowerWithUnsignedExponent(base, exponent >> 1);
result *= result;
if (exponent & 0x1 == 1)
result *= base;
return result;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：数值的整数次方 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)