階乗プログラムを書き留めています。プログラム全体が完成しましたが、問題なく動作しています。ただし、出力を次のようにしたい
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