✔ 最佳答案
首先, 參考維基百科,
N! = N * (N-1)!
0! = 1
如果用上述程式段計算0!, 會出現錯誤(堆疊記憶體秏盡),
首先factorial中, IF語句條件應更改為:
if ( n <= 1 )
另為解答你問題, 以下是空運行:
factorial(5)
= 5 * factorial(4) // return n*factorial(n-1)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1 // return 1
= 120
所以輸出是:
5! = 120
ps. 5! = factorial(5)
2012-03-08 20:32:17 補充:
factorial(5)
= 5 * factorial(5-1) // return n*factorial(n-1)
= 5 * factorial(4)
= 5 * (4 * factorial(4-1)) // return n*factorial(n-1)
= 5 * 4 * factorial(3)
= 5 * 4 * (3 * factorial(3-1))
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(2-1)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
2012-03-08 20:32:41 補充:
= 20 * 6
= 120