我在讓我的計數器在我的遞回中作業時遇到問題,而不是列印 11,而是列印 11,1s。我在哪里犯了錯誤?
def power(x, n):
global countcalls # note countcalls variable is in my global and it is equal to 0
countcalls = 1
print(countcalls)
if n <= 0:
return 1
else:
return x * power(x, n-1)
我的輸出:
1
1
1
1
1
1
1
1
1
1
1
1024
想要的輸出:
11
1024
uj5u.com熱心網友回復:
首先,countcalls = 1不增加變數,它只是將它設定為1. 要增加,請使用 = 1,而不是= 1。
其次,如果您只想在最后列印,請將print()呼叫放在基本案例中。
不要使用全域變數,而是使用另一個默認為 的引數0。
def power(x, n, countcalls = 0):
countcalls = 1
if n <= 0:
print(countcalls)
return 1
else:
return x * power(x, n-1, countcalls)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359901.html
