在 Java 中使用递归的阶乘 [英] Factorial using Recursion in Java
问题描述
我正在使用 Java: The Complete Reference 一书学习 Java.目前我正在研究递归主题.
请注意:stackoverflow 上也有类似的问题.我搜索了它们,但没有找到我的问题的解决方案.我对以下程序中的逻辑感到困惑.
如果我运行下面的程序,它会产生正确的输出,但我不明白其中的逻辑.
- 我不明白下面这行的逻辑:result = fact(n-1) * n;
- 据我所知,如果我们传递 n=4 的值,如下面的程序所示,
- 然后,3 * 4 存储在结果中,即 12.
- 再次调用 fact(n-1).然后 n 变为 3.
- 然后将 2 * 3 存储在结果中,替换之前的 12.
我想你明白我的困惑/困惑在哪里.
谢谢.
类计算{事实上(int n){整数结果;如果(n==1)返回 1;结果 = 事实(n-1)* n;返回结果;}}公共类阶乘{公共静态无效主(字符串参数[]){计算 obj_one = new Calculation();int a = obj_one.fact(4);System.out.println("这个数的阶乘是:" + a);}}
result
是 fact
方法的局部变量.因此,每次调用 fact 方法时,结果都存储在与上一次调用 fact 不同的变量中.
所以当以 3 为参数调用 fact 时,你可以想象它的结果是
result3 = fact(2) * 3结果3 = 结果2 * 3结果 3 = 1 * 2 * 3
I am learning Java using the book Java: The Complete Reference. Currently I am working on the topic Recursion.
Please Note: There are similar questions on stackoverflow. I searched them but I didn't find the solution to my question. I am confused with the logic in the following program.
If I run the below program, it produces the correct output, but I didn't understand the logic.
- I didn't understand the logic in the following line : result = fact(n-1) * n;
- From my knowledge, If we pass the value of n=4 as shown in the below program,
- Then, 3 * 4 is stored in the result i.e., 12.
- Again, fact(n-1) is called. Then n becomes 3.
- Then the 2 * 3 is stored in the result replacing the previous 12.
I think you understood where I am stuck up/confused.
Thank you.
class Calculation { int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; } } public class Factorial { public static void main(String args[]) { Calculation obj_one = new Calculation(); int a = obj_one.fact(4); System.out.println("The factorial of the number is : " + a); } }
result
is a local variable of the fact
method. So each time the fact method is called, the result is stored in a different variable than the previous fact invocation.
So when fact is invoked with 3 as argument, you can imagine that its result is
result3 = fact(2) * 3
result3 = result2 * 3
result3 = 1 * 2 * 3
这篇关于在 Java 中使用递归的阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!