简体   繁体   English

Java中的阶乘递归“可视化”

[英]factorial recursion “visualized” in java

So I have this basic factorial calculator in java but I am having trouble modifying it to fit the exercise. 所以我在Java中有这个基本的阶乘计算器,但是在修改它以适应练习时遇到了麻烦。 It says: Modify the factorial method to print its local variable and recursive-call parameter. 它说:修改阶乘方法以打印其局部变量和递归调用参数。 For each recursive call,display the outputs on a separate line and add a level of indentation. 对于每个递归调用,在单独的行上显示输出并添加缩进级别。 I think Im having trouble understanding where the print statements should go. 我认为我在理解打印声明应去的地方时遇到麻烦。 So does local variable = number and recursion call parameter = number-1. 局部变量= number以及递归调用参数= number-1也是如此。 Here is my code so far. 到目前为止,这是我的代码。

public class Factorial {
    private static String s1="";
    public static long factorial(long number,long save) {


    if (number <= 1) { //test for base case
        System.out.printf("%s%d! = %d*%d!=  ",s1,save,save,save-1);
        s1 = s1 +" ";
        return 1;
    }
    else{ //recursion step
        return number * factorial(number - 1,save);
    }
}

//output factorial for values 0-21
public static void main(String[] args) {
    //calculate factorials 0-21
            for (int counter = 0; counter <= 21; counter++){
                long x = factorial(counter,counter);
        System.out.printf("%d%n",x);
    }
}

}

I think Im having trouble understanding where the print statements should go. 我认为我在理解打印声明应去的地方时遇到麻烦。

Yes, indeed. 确实是的。 As you can see, the exercise states 如您所见,练习状态

Modify the factorial method to print its local variable and recursive-call parameter. 修改阶乘方法以打印其局部变量和递归调用参数。

So, modify factorial instead of main . 因此,修改factorial而不是main This way, each time factorial is invoked, you get a new line printed out, just as the exercise asks. 这样,每次调用factorial时,都会按照练习的要求打印出新行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM