运行 我的程序出现无限循环。我如何解决它?

I am getting an infinite loop when I run my program. How do I fix it?

Output of the code 这是我正在研究的一个财务问题。我设置了一个循环,但在它显示所有正确值后,它无限地显示每个变量的所有“0”。我的 Python 版本是 Ubuntu 上的 3.6.7 运行。

我已尝试将其设置为 current_balance 大于 ending_balance,但问题仍然存在。

price = float(input("Enter initial price: "))
INTEREST_RATE = 0.12 / 12
DOWN_PAYMENT = price * .9
monthly_payment = 0
ending_balance = 0
interest = 0
principal = 0
month = 0

print("%s%18s%10s%11s%9s%13s" % ("Month", "Current Balance", "Interest", "Principal", "Payment", "End Balance"))

month = 1
current_balance = DOWN_PAYMENT
interest = current_balance * INTEREST_RATE
monthly_payment = current_balance * 0.05
principal = monthly_payment - interest
ending_balance = current_balance - principal

while ending_balance > 0:
    print("%d%18.2f%10.2f%11.2f%9.2f%13.2f" % (month, current_balance, interest, principal, monthly_payment, ending_balance))
    month += 1
    current_balance = ending_balance
    interest = current_balance * INTEREST_RATE
    monthly_payment = current_balance * 0.05
    principal = monthly_payment - interest
    ending_balance = current_balance - principal

没有错误,只是无限循环。程序应该结束一次 ending_balance = 0.

浮点数是你的问题。要结束循环,请使用:

while ending_balance >= 0.005:

当前余额一直在变小,但是你只显示两位小数。