我目前正在研究一个问题,该问题要求制定一个程序,确定固定的每月付款以偿还一定数额的债务。
出于某种原因,当我将MP值增加少于70时,此代码进入无限循环。如果我使用70和更高的值,建议的每月付款是远离的。
def NoDebt(balance, annualInterestRate):
'''
balance -> int/float, the amount of debt youre in
annualInterestRate --> interest rate (divide by % 100 first)
'''
balance0 = balance
month = 0
MIR = annualInterestRate/12.0
MP = 10
while balance > 0:
balance = balance0
MP = MP + 10
while month < 12:
MUB = balance - MP
balance = MUB + (MIR*MUB)
month = month + 1
return MP
我已经运行了这个并且暂时谈了一段时间 - 不知道为什么它不起作用。
有人有任何建议吗?
答案 0 :(得分:0)
此循环只执行一次:
while month < 12:
MUB = balance - MP
balance = MUB + (MIR*MUB)
month = month + 1
一旦完成,外部循环的后续迭代将不会进入此内部循环。因为month
仍然是,永远将是12.所以代码只是无限期地重复这个:
while balance > 0:
balance = balance0
MP = MP + 10
只要balance0
大于0,就没有理由不会停止。
您需要在外部循环中重置month
:
while balance > 0:
month = 0
balance = balance0
MP = MP + 10
while month < 12:
MUB = balance - MP
balance = MUB + (MIR*MUB)
month = month + 1
注意: 可能是您代码中的其他逻辑错误,但这似乎很重要。例如,正如上面的评论中所指出的,您的循环似乎始终将balance
重置为“每12个月”的原始余额。仍然强烈建议您使用调试器,甚至是笔和纸。 This通常可以帮助阅读这个主题。