我有一個因子程序寫下來。我已經完成了整個程序,運行沒有任何問題。 不過,我想輸出看起來像這樣因子程序打印出遞歸
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
當然,然後你失去了你的漂亮的尾遞歸設置。但對於一個可能不是世界末日的玩具例子來說。 – dfreeman 2013-04-23 21:49:04
@dfreeman'return num * factorial(num-1);'不是尾遞歸的。不過,一個好的編譯器可以將它轉換爲尾遞歸(或迭代),但它並不重要。 – 2013-04-23 22:43:07
@danielfischer哎呀,你是對的。我沒有想到 - 我的壞評論。 – dfreeman 2013-04-24 15:15:20