[英]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;
}
}
If exponent is negative 1.0 is returned but that is wrong. 如果指数为负,则返回1.0,但这是错误的。 For eg hoch(2,-2) it should be 0.25.
例如hoch(2,-2)应该为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). 并且您希望乘以的东西是
1/basis
(“剥离”一个负指数)。
With hoch(2,-2) you actually calculate 使用hoch(2,-2)实际计算
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: 将BASE提升为pos或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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.