为什么我的代码会出现无限循环?

时间:2016-01-28 21:03:47

标签: python-2.7

minimunpaymonth = 0
balance = 4773
annualInterestRate = 0.2
def function(minimunpaymonth):
    global balance
    month = 1
    while month <= 12:
        balance = balance - minimunpaymonth
        anninterest = annualInterestRate/12 * balance
        balance = balance + anninterest
        month += 1
    return balance
while function(minimunpaymonth) >= 0:
    minimunpaymonth += 10
print "Lowest Payment: " + str(minimunpaymonth)

第二个while循环是无限的,我不知道为什么。第一个是好的,因为我已经运行了

当循环增加minimunpaymonth时,平衡值会下降,所以会有一个平衡为负的时刻

def function(minimunpaymonth, balance, annualInterestRate):
    month = 1
    while month <= 12:
        balance = balance - minimunpaymonth
        anninterest = annualInterestRate/12 * balance
        balance = balance + anninterest
        month += 1
    return balance
while function(minimunpaymonth, balance, annualInterestRate) >= 0:
    minimunpaymonth += 10
print "Lowest Payment: " + str(minimunpaymonth)
好吧,我刚解决了。我改变函数给出3个参数而不是1

2 个答案:

答案 0 :(得分:1)

你的第二个循环正在检查minimunpaymonth是否为>= 0,如果是,那么它会再次执行循环。

minimunpaymonth始终为>=0,因为它始于0&amp;只是添加到。此值没有减法。

答案 1 :(得分:0)

第二个循环不断添加到最小付款,它将始终>&0;直到它达到变量的数字限制;然而正如评论指出的那样,“功能”可能会变得更少,但也许利率始终保持在零以上且最低支付不能实现它 - 在现实生活中足够可信!