Java:简单的递归函数仅返回1
奇怪的是,这是我的第一个 Java 应用程序,我想实现一个任意精度的阶乘函数,我很好地完成了递归函数,但我的迭代函数仅输出“1”,没有其他内容。对我来说太晚了,我无法找出原因,我不确定我哪里出错了,这里有明显的东西吗?
public static BigInteger ifact(BigInteger n) {
BigInteger ret = new BigInteger("1");
BigInteger i = new BigInteger("1");
for(i = new BigInteger("0"); i.compareTo(n) == 0; i.add(new BigInteger("1"))){
ret.multiply(i);
}
return ret;
}
如果您没有注意到它使用 BigInteger 包,那么就会出现奇怪的文字。
另外,像 C 一样,您可以做一些类似于 typedef 的事情,这样我就不需要每次都输入“BigInteger”吗?
编辑:我想我的意思是将ret
设置为n
,可能是这样,也可能不是。
This is oddly my first Java application, I was wanting to implement an arbitrary precision factorial function, I did the recursive one fine but my iterative one simply outputs "1" and nothing else.. It is so late for me I can not spot why, I am not sure where I went wrong, is there something obvious here?
public static BigInteger ifact(BigInteger n) {
BigInteger ret = new BigInteger("1");
BigInteger i = new BigInteger("1");
for(i = new BigInteger("0"); i.compareTo(n) == 0; i.add(new BigInteger("1"))){
ret.multiply(i);
}
return ret;
}
In case you did not notice it uses the BigInteger package, hense the odd writings..
Also, like C, can you do something similar to typedef so I don't need to type "BigInteger" each time?
EDIT: I think I meant to set ret
as n
, that may be it, or..maybe not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
回答你的“typedef”问题,不,你不能在Java中做到这一点。
至于你的代码,它有很多错误。你的循环只会执行一次,并且仅当 n 等于 i 时。为什么在循环开始时将 i 初始化为 1,然后初始化为 0?为什么忽略
i.add(...)
的结果?为什么忽略 ret.multiply(i) 的结果?请记住,这些方法不会改变 BI 本身!这包含了这些变化:
In answer to your "typedef" question, no, you can't do that in Java.
As for your code, it has numerous mistakes. Your loop will only ever execute once, and only if n is equal to i. Why do you initialize i to 1 and then 0 at the beginning of the loop? Why do you ignore the result of
i.add(...)
? Why do you ignore the result ofret.multiply(i)
? Remember, these methods don't change the BI itself!This incorporates those changes:
尝试更改
为
Try changing
to
BigInteger 对象是不可变的(意味着您无法更改它)。这样,它就像一个 String 对象。因此,为了使其发挥作用,您需要将线路更改
为
The BigInteger object is immutable (meaning you can't change it). In this way, it's like a String object. So, for this to work, you would want to change your line
to