我对递归的了解是函数调用自身 并且它具有停止的基本条件。我的教授写了一个程序,他说程序中发生了递归,我说不,不是。我对此感到困惑。所以我请你消除我的困惑。他制作的程序代码如下:
int fact(int n) {
if (n == 0) {
return 1;
}
for (int i = n; i >= 1; i--) {
s1.push(i);
}
return Return_result();
}
int Return_result() {
int f = 1;
while (s1.top != -1) {
f = f * s1.pop();
}
return f;
}
最佳答案
你是对的,所提供的代码中没有递归。这是一种迭代方法。
递归是,如果在 f()
方法(在 Java 命名法中)或函数(通常)中,您有一个对 f()
的调用。
递归方法如下所示:
int fact(int n) {
return (n <= 1) ? 1 : fact(n - 1) * n;
}
或者,使用 tail-recursion (也称为“尾调用”):
int fact(int n) {
return factTail(n, 1);
}
int factTail(int n, int accumulator) {
return (n <= 1) ? accumulator : factTail(n - 1, n * accumulator);
}
目前,JVM 不执行尾递归优化,但是 this can change :
It's important to note that this isn't a bug in the JVM. It's an optimization that can be implemented to help functional programmers who use recursion, which is much more common and normal in those languages. I recently spoke to Brian Goetz at Oracle about this optimization, and he said that it's on a list of things to be added to the JVM, but it's just not a high-priority item. For now, it's best to make this optimization yourself, if you can, by avoiding deeply recursive functions when coding a functional language on the JVM.
关于java - Java阶乘程序中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26817849/