问题描述
result
是方法的局部变量fact
。因此,每次调用事实方法时,结果都存储在与先前的事实调用不同的变量中。
因此,当以3作为参数调用事实时,您可以想象其结果是
result3 = fact(2) * 3
result3 = result2 * 3
result3 = 1 * 2 * 3
解决方法
我正在使用《 Java:完整参考》这本书来学习Java。目前,我正在从事递归主题。
请注意: 关于stackoverflow也有类似的问题。我搜索了它们,但没有找到解决问题的方法。我对以下程序中的逻辑感到困惑。
如果我运行下面的程序,它将产生正确的输出,但是我不理解其逻辑。
- 我不理解以下行中的逻辑: result = fact(n-1)* n;
- 据我所知,如果我们按以下程序所示传递n = 4的值,
- 然后,将3 * 4存储在结果中,即12。
- 再次,事实(n-1)被调用。然后n变成3。
- 然后将2 * 3存储在结果中,以替换之前的12。
-
我认为您了解我被困住/感到困惑的地方。
-
谢谢。
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); } }