如何修复此代码以获得正确的输出

时间:2018-09-27 23:37:54

标签: python-3.x

这是代码:

amount_borrowed = float(input("Amount borrowed: $"))
interest_rate = float(input("Interest rate: "))
loan_length = int(input("Length of loan (months): "))
i = interest_rate/100
monthly_payment1 = (i / 12) * amount_borrowed    #this is the first part of the payment formula

monthly_payment2 = monthly_payment1 / 1 - (1 + i / 12)**-loan_length          
#second part of monthly payment formula

print("The monthly payment is ${:.2f}" .format(monthly_payment2))

我应该得到以下输出:

借款金额:$ 100.00

利率:10.0

贷款期限(月):12

每月付款$ 8.79。

我继续得到这个:

借款金额:$ 100

利率:10

贷款期限(月):12

每月支付$ -0.07

1 个答案:

答案 0 :(得分:2)

除以1并没有多大意义,我认为您确实忘记了除法分母中的一对括号。因此,以下一行

monthly_payment2 = monthly_payment1 / 1 - (1 + i / 12)**-loan_length

应该是

monthly_payment2 = monthly_payment1 / (1 - (1 + i / 12)**-loan_length)

我在这里进行了测试,并获得了$8.79的期望值