Calculate the power of any exponent (negative or positive)
I want to calculate the result, given any exponent (negative or positive) and a base of type integer. I am using recursion:
public static double hoch(double basis, int exponent) {
if (exponent > 0) {
return (basis * hoch(basis, exponent - 1));
} else if (exponent < 0) {
return ((1 / (basis * hoch(basis, exponent + 1))));
} else {
return 1;
}
}
开发者_C百科
If exponent is negative 1.0 is returned but that is wrong. For e.g. hoch(2,-2) it should be 0.25. Any ideas what could be wrong?
}else if(exponent < 0){
return ((1/(basis*hoch(basis, exponent+1))))
should be
}else if(exponent < 0){
return (1/hoch(basis, -exponent));
public static double hoch(double basis, int exponent){
if(exponent > 0){
return basis*hoch(basis, exponent-1);
}else if(exponent < 0){
return hoch(basis, exponent+1)/basis;
}else{
return 1;
}
}
although the more efficient (recursive) solution is
public static double hoch(double basis, int exponent){
if(exponent == 0)
return 1;
else{
double r = hoch(basis, exponent/2);
if(exponent % 2 < 0)
return r * r / basis;
else if(exponent % 2 > 0)
return r * r * basis;
else
return r * r;
}
}
Your parentheses are the wrong way around. You want to be multiplying by the result of the recursive call, not dividing by it; and you want the thing you multiply by to be 1/basis
(which "peels off" one negative exponent).
With hoch(2,-2) you actually calculate
1 / (-2 * (1 / (-1 * (1 / 1)))
<=> 1 / (-2 * (1 / (-1))
<=> 1 / (-2 * -1)
<=> 1/2
Working code for raising BASE to a pos or neg BASE:
FUNC Raise_To_Power
LPARAMETERS pnBase, pnPow
DO CASE
CASE pnPow = 0
RETURN 1
CASE pnPow > 0
RETURN pnBase * Raise_To_Power(pnBase, pnPow-1)
CASE pnPow < 0
RETURN 1 / (pnBase * Raise_To_Power(pnBase, -(pnPow+1)))
ENDCASE
ENDFUNC
精彩评论