为什么我的代码中有无限循环?

时间:2016-09-27 19:59:38

标签: python python-3.x infinite-loop

下面我有一段用于计算信用卡余额的代码,但当balance具有极值(例如下面的balance=9999999999)时,它不起作用。它通过无限循环抛出代码。我有几个关于如何解决这个缺陷的理论,但不知道如何推进它们。这是我的代码:

balance = 9999999999
annualInterestRate = 0.2
monthlyPayment = 0

monthlyInterestRate = annualInterestRate /12
newbalance = balance
month = 0

while newbalance > 0:
    monthlyPayment += .1
    newbalance = balance

    for month in range(1,13):
        newbalance -= monthlyPayment
        newbalance += monthlyInterestRate * newbalance
        month += 1
print("Lowest Payment:" + str(round(monthlyPayment,2)))

我的理论是这样的 while newbalance > 0 导致无限循环,因为newbalance总是大于0.

如何更改此while循环,以免导致我的代码无限运行?

顺便说一下: 程序适中,程序运行很长时间,最后给出答案。对于较大的数字,该计划只是继续。

2 个答案:

答案 0 :(得分:3)

此循环不是无限的,但需要很长时间才能解决。对于非常大的balance值,monthlyPayment必须变得非常大才能将其降至零以上。

答案 1 :(得分:0)

如果允许在你的作业中使用它,那么二分法将会更快地执行。但是,如果您需要将每月付款增加0.01,则无法帮助您。

static_balance = balance
interest = (annualInterestRate/12)
epsilon = 0.01
lo = balance/12
hi = balance

while abs(balance) > epsilon:
    balance = static_balance
    min_pmt = (hi+lo)/2
    for i in range(12):
        balance -= min_pmt
        balance *= 1+interest
    if balance > 0:
        lo = min_pmt
    else:
        hi = min_pmt
print("Lowest payment: ", round(min_pmt, 2))
相关问题