使用Java中的递归的因子 [英] Factorial using Recursion in Java
问题描述
我正在使用Java:The Complete Reference这本书学习Java。
目前我正在研究Recursion主题。
I am learning Java using the book Java: The Complete Reference. Currently I am working on the topic Recursion.
请注意: stackoverflow上有类似的问题。我搜查了他们,但我找不到解决问题的方法。我对以下程序中的逻辑感到困惑。
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.
- 我不理解以下行中的逻辑: result = fact(n-1)* n;
- 据我所知,如果我们传递n = 4的值,如下面的程序所示,
- 那么,3 * 4存储在结果ie,12。
- 再次,调用fact(n-1)。然后n变为3.
- 然后2 * 3存储在结果中,取代之前的12。
-
我想你明白了我感到困惑/困惑。
- 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.
谢谢。
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
是 fact
方法的局部变量。因此,每次调用事实方法时,结果都存储在与前一个事实调用不同的变量中。
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.
因此,当使用3作为参数调用fact时,您可以想象它的结果是
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屋!