计算任何指数的幂(负或正)
我想计算结果,给定任何指数(负或正)和整数类型的基数。我正在使用递归:
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;
}
}
如果指数为负数,则返回 1.0,但这是错误的。对于例如 hoch(2,-2),它应该是 0.25。有什么想法可能是错的吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
应该是
should be
尽管更有效的(递归)解决方案是
although the more efficient (recursive) solution is
你的括号是错误的方式。您想要乘以递归调用的结果,而不是除以它;并且您希望乘以
1/basis
(“剥离”一个负指数)。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).使用 hoch(2,-2) 你实际上计算
With hoch(2,-2) you actually calculate
将 BASE 提升为正或负 BASE 的工作代码:
Working code for raising BASE to a pos or neg BASE: