为什么第一个 python 递归程序不起作用?

Why did the first python recursion program did not work?

我在edx上回答过这个问题:写一个程序,计算如果一个人每个月只支付信用卡公司要求的最低月供,一年后的信用卡余额。

我能够使用迭代过程来回答问题,但我尝试使用递归。我设法解决了递归问题。

我的问题是为什么我的第一个递归代码不起作用并产生了无限循环。 我只是一个初学者,只是想提高我的知识。非常感谢你帮助我

''' 这是我的第一个代码 ''''

def recur(balance,n):
    if n < 1:
        return balance
    else:
        return ((1+monthly_interest_rate)*(recur(balance, n-1)) - (minimumPaymentRate*(recur(balance, n-1)))) balance = 42
annualInterestRate = 0.2
n = 12
minimumPaymentRate = 0.04
monthly_interest_rate = annualInterestRate/12.0
recur(balance, n)

''' 第二个代码有效 '''

def recur(balance,n):
    if n < 1:
        return balance
    else:
        bal_recur = recur(balance, n-1)
        payment_made = (minimumPaymentRate*bal_recur)
        return ((1+monthly_interest_rate)*(bal_recur - payment_made))

balance = 42
annualInterestRate = 0.2
n = 12
minimumPaymentRate = 0.04
monthly_interest_rate = annualInterestRate/12.0
recur(balance, n)

您的第一个代码中有 1 个错误:

def recur(balance,n):
    if n < 1:
        return balance
    else:
        return ((1+monthly_interest_rate)* ( (recur(balance, n-1)) - (minimumPaymentRate*(recur(balance, n-1))) ) ) #here you need to add 2 parenthesis like you do in your second code
balance = 42
annualInterestRate = 0.2
n = 12
minimumPaymentRate = 0.04
monthly_interest_rate = annualInterestRate/12.0
recur(balance, n)