拜托,我正在努力找出我的推理有什么问题,因此我的结果。 我正在学习一门在线课程,在这门课程中,我应该计算出在12个月内消除信用卡债务所需的最低金额。我得到了一个年利率,一个债务金额(余额)的值,以及一个每月还款额应该增加的值(10的倍数)。 根据我的推理,我生成的代码应该在几个月内迭代,但是如果余额值不为零,它应该增加每月的付款并重新计算。 我的价值观(我认为)与预期结果略有出入。我的代码是这样的:
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
monthlyPayment = 10
while (balance > 0):
for each in range(0, 12):
balance = balance - monthlyPayment
balance = balance + (monthlyInterestRate * balance)
if (balance > 0):
monthlyPayment += 10
else:
break
print monthlyPayment
余额=3329,年利率0.2, 我的结果是:310(正确)
余额=4773,年利率0.2, 我的结果是:380(不正确,应该是440)
余额=3926,年利率为0.2, 我的结果是:340(不正确,应该是360)。在
有人能帮我指点我哪里错了吗?在
谢谢!在
你快到了。在你的实现中有一些问题。在
首先,你需要在意识到之前测试过的每月付款没有支付之后重置余额。在
其次,你检查平衡并增加平衡的方法是错误的。现在,你每个月要多付10美元,如果我能理解你的问题并不是你想要的。你想增加月供,因为你看到少付的10美元在12个月内没有还清。在
正如另一点一样,您的
else: break
是不必要的,因为当它进入下一个迭代时,它将脱离while
循环。在这个怎么样:
我所做的基本上是把if条件从for each中去掉,并使用一个副本进行平衡。while(running)实质上迭代monthlyPayment的可能值。在
(如果早些时候设置了currentBalance,您可以使用while(currentBalance>;0),但我会使用while(running)方法,因此它的读取方式类似于do-until循环)
全年支付的余额应该是相同的,这样
if
里面的for each
就没有意义了。不需要if
。当尝试新的每月付款时,余额需要重置为起始值。
我尝试了这些更改,它与您的测试用例相匹配。在
相关问题 更多 >
编程相关推荐