【发布时间】:2017-06-17 08:27:01
【问题描述】:
我正在创建一个简单的模型,用于计算在 12 个月内还清信用卡余额所需的最低每月固定付款额。
我的代码:
balance = 3329 # starting balance
annualInterestRate = 0.2 # yearly interest rate
minFixedPayment = 0 # initiate a minimum monthly payment of 0
while balance > 0:
minFixedPayment = minFixedPayment + 10
for i in range(1,13,1):
unpaidBalance = balance - minFixedPayment
balance = unpaidBalance + ((annualInterestRate/12) * unpaidBalance)
i=i+1
print(round(minFixedPayment,2))
我在 for 循环之前添加了“minFixedPayment”增量,以便它不断增加,直到在第 12 个月末找到余额
我已经尝试添加
minFixedPayment = minFixedPayment + 10
声明到循环结束,像这样:
while balance > 0:
for i in range(1,13,1):
unpaidBalance = balance - minFixedPayment
balance = unpaidBalance + ((annualInterestRate/12) * unpaidBalance)
i=i+1
minFixedPayment = minFixedPayment + 10 # moved this to after the loop
print(round(minFixedPayment,2))
但这会使 while 循环永远运行(为什么?)。
有没有更好的方法来解决这个问题? 感谢您的宝贵时间。
【问题讨论】:
-
为什么不以
minFixedPayment = -10开头并打印/返回max(0, round(minFixedPayment,2))? -
另外,您正在计算 3329 的 20% 利息贷款并支付 10 美元,很可能您永远不会还清。
-
一般建议:放弃 while 循环并设置运行时或迭代的上限。接下来,为了保持稳健,您可能需要检查余额何时降至一美分以下,而不是像@ChihebNexus 指出的那样低于零。
-
@trincot 聪明!但仍然使while循环永远运行:(
-
@RYS 只是采样值,为一个类做这个:) 我会尝试在循环上设置一个不同的上限,谢谢!
标签: python loops for-loop while-loop