def fact(n):if n <= 1:return 1temp = fact(n-1)product = temp * nreturn productprint(fact(4))最后結果是24,請解釋一下為什么最后temp=6的時候n=4,謝謝!
1 回答

青春有我
TA貢獻1784條經驗 獲得超8個贊
1、這是遞歸;
2、遞歸過程中,第一層運算時n=4,則n-1=3,這個時候temp=fact(n-1),也就是temp=fact(3)。但由于遞歸沒有完成,這個時候會通過計算temp=fact(2),temp=fact(1)兩層遞歸返回temp=fact(3)的值,也就是1*2*3=6.
3、就是說在遞歸過程內部最高算到fact(n-1)的值,遞歸結束時才返回n*fact(n-1)的值。
添加回答
舉報
0/150
提交
取消