java 计算任何指数的幂(负或正)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4364634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate the power of any exponent (negative or positive)
提问by Upvote
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. For e.g. hoch(2,-2) it should be 0.25. Any ideas what could be wrong?
如果指数为负,则返回 1.0 但这是错误的。例如,hoch(2,-2) 应该是 0.25。任何想法可能是错误的?
回答by The Archetypal Paul
}else if(exponent < 0){
return ((1/(basis*hoch(basis, exponent+1))))
should be
应该
}else if(exponent < 0){
return (1/hoch(basis, -exponent));
回答by dspyz
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;
}
}
回答by Andreas Dolk
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
回答by Karl Knechtel
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
(“剥离”一个负指数)。
回答by Bogdan Butnaru
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