我写了一个阶乘程序。我已经完成了整个程序,它运行没有任何问题。但是,我希望输出看起来像这样
Begin Factorial Program. . .
Provide number and the factorial will be computed: 4
4! is . . .
In f(4) and calling f(3) . . .
In f(3) and calling f(2) . . .
In f(2) and calling f(1) . . .
In f(1) and calling f(0) . . .
In f(0) and computing f(0). Returning 1
f(1) is 1 * 1 which equals 1. Returning
f(2) is 2 * 1 which equals 2. Returning 2
f(3) is 3 * 2 which equals 6. Returning 6
f(4) is 4 * 6 which equals 24. Returning 24
4! = 24
我怎么得到。
f(1) is 1 * 1 which equals 1. Returning
f(2) is 2 * 1 which equals 2. Returning 2
f(3) is 3 * 2 which equals 6. Returning 6
f(4) is 4 * 6 which equals 24. Returning 24
用我的方法打印出来
这是我的方法
public static int factorial(int num) {
if (num == 0) {
System.out.println("In f(" + num + ") and computing f(" + num
+ "). Returning " + 1);
return 1;
} else {
System.out.println("In f(" + num + ") and calling f(" + (num - 1)
+ ") . . .");
return num * factorial(num - 1);
}
打印出来
4! is . . .
In f(4) and calling f(3) . . .
In f(3) and calling f(2) . . .
In f(2) and calling f(1) . . .
In f(1) and calling f(0) . . .
In f(0) and computing f(0). Returning 1
4! = 24