gpt4 book ai didi

java - 如何理解java中递归的概念?

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:48 25 4
gpt4 key购买 nike

我是java编程新手,我们的老师教了我们递归的概念,我发现它有点复杂。我只知道它的工作原理就像一个循环(就像 4 的阶乘),但我仍然不太明白为什么它会这样工作。我可以获得有关该主题的详细解释吗?这是我老师用来解释的一段代码和一张图片。

package javaapplication1;

public class JavaApplication1 {

static int factorial(int n){
int t;
if(n == 0){
return 1;
} else {
t = factorial(n - 1);
return n * t;
}
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}

下图中,蓝色代表堆栈缠绕,绿色代表堆栈展开,我又不知道什么是堆栈缠绕和展开。

/image/pjqJy.png

最佳答案

递归函数是一种调用自身的函数,直到到达 return 语句为止,从而阻止它调用自身。以阶乘函数为例。阶乘是一个数学函数,返回数字与其自身相乘 - 1 与其自身相乘 - 2, ... 乘以 1,例如:5 的阶乘 = 5! = 5x4x3x2x1 = 120。它也等于自身乘以自身的阶乘-1,即:5! = 5x4!考虑到 0! = 1。为了在 Java 代码中表示这一点,您需要一个循环来乘以从 1 开始的数字,一直到您要计算其阶乘的数字。此外,解释一下您的代码,让我们计算 Factorial(5):Factorial() 返回一个整数。

Initial Call from main(): 5 != 0, then skip the condition (n == 0); t = Factorial(5-1) = Factorial(4);

Second call from Factorial(4): 4 != 0, then skip the condition (n == 0); t = Factorial(4-1) = Factorial(3);

Third call from Factorial(3): 3 != 0, then skip the condition (n == 0); t = Factorial(3-1) = Factorial(2);

Fourth call from Factorial(2): 2 != 0, then skip the condition (n == 0); t = Factorial(2-1) = Factorial(1);

Fifth call from Factorial(1): 1 != 0, then skip the condition (n == 0); t = Factorial(1-1) = Factorial(0);

Sixth call from Factorial(0): 0 == 0, then return value 1;

First return, 1, to Fifth call (Factorial(1)): return n*t = return 1*1 = return value 1;

Second return, 1, to Fourth call (Factorial(2)): return n*t = return 2*1 = return value 2;

Third return, 2, to third call (Factorial(3)): return n*t = return 3*2 = return value 6;

Second return, 6, to second call (Factorial(4)): return n*t = return 4*6 = return value 24;

Second return, 24, to First call (Factorial(5)): return n*t = return 5*24 = return value 120;

Second return, 120, to Initial call (from main()): print(120);

希望这可以帮助您理解递归。

关于java - 如何理解java中递归的概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26041546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com