Solution One: a bad solution
Double Power (double base,int exponent)
{
Double result=1.0;
for (int i=1;i<=exponent;++i)
Result*=base;
return result;
}
Solution one does not consider the case of exponential 0 and negative numbers, only the case that the exponent is positive is considered.
Solution Two: A comprehensive but not efficient solution
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;
}
Solution Three: A comprehensive and efficient solution
Use a formula to find the n-th side of a:
The double powerwithunsignedexponent function of the solution two is modified to:
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;
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Integer number of values