所以我在java中有这个基本的阶乘计算器,但我在修改它以适应练习时遇到了困难。它说:修改阶乘 方法打印其局部变量和递归调用参数。对于每个递归调用,将输出显示在单独的行上并添加一定程度的缩进。我认为我无法理解打印语句应该放在哪里。局部变量 = number 和递归调用参数 = number-1 也是如此。这是到目前为止我的代码。
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.
是的,确实如此。如您所见,练习指出
Modify the factorial method to print its local variable and recursive-call parameter.
因此,修改 factorial
而不是 main
。这样,每次调用 factorial
时,您都会打印出一个新行,正如练习所要求的那样。
关于java - java中的阶乘递归 "visualized",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36391574/