Python简单利息计算

2024-04-18 00:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在计算每月要付多少钱才能在12个月内还清贷款。使用10美元作为增量。在

Payment = 0
balance = float (1200)
interest = float (0.18)
MonthlyInt = interest/12.0

while balance > 0 :

    Payment = Payment + 10
    month = 0
    while month < 12 and balance > 0:
        IntPay = balance* MonthlyInt
        balance += IntPay
        balance -= Payment
        month += 1
print Payment

正确答案应该是110,为什么我得到60?在


Tags: and答案paymentfloat增量printbalancewhile
2条回答

这是另一种方法。我试着在麻省理工学院的edx课程中使用Brians的例子,但没能让它在所有情况下都起作用。在

我就是这样做的。在

def lowestpayment(x,y):
""" x = total balance due
    y = annual interest rate 
    Returns min payment needed to pay off debt in 1 year
"""
month = 0
balance = x
annualInterestRate = y
payment = 0
while balance > 0 and month <= 12:
    month = 0
    balance = x
    payment += 10
    balance = balance - payment
    monthlyint = balance*annualInterestRate/12
    balance += monthlyint
    month += 1
    if balance+(balance*annualInterestRate/12)*11-payment*12 <= 0:
        return payment


print("Lowest Payment: ",lowestpayment(35,0.25))

产生差异的主要原因是:

  • 在再次循环12个月之前,余额应重置为1200
  • 在计算利息之前,这笔款项应该从余额中扣除

一些更小的python功能是:

  • float()不需要围绕0.18这样的数字,它已经是一个浮点数了
  • 1200.表示该数字是一个浮点数,因此不需要float()

那么,考虑一下这些事情:

Payment = 0
interest = 0.18
MonthlyInt = interest/12.0
balance = 1200.

while balance > 0 :

    Payment = Payment + 10
    month = 0
    balance = 1200.
    while month < 12 and balance > 0:
        balance -= Payment
        IntPay = balance* MonthlyInt
        balance += IntPay
        month += 1
print(Payment)

给出110的结果。在

相关问题 更多 >

    热门问题