请让我找出我的推理有什么问题,因此我的结果。我正在学习一门在线课程,在这门课程中,我应该计算出在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)。
有人能帮我指点我哪里错了吗?
谢谢!
发布于 2016-01-28 16:46:56
你快到了。在您的实现中存在一些问题。
首先,你需要重新设置余额后,意识到之前测试的每月付款没有,嗯,支付。
其次,检查余额并增加余额的选项卡是错误的。就目前情况而言,你每月多付10美元,如果我正确理解你的问题,这不是你想要的。你想增加每月付款后,看到一个10美元,但没有支付它在12个月。
作为另一点,您的else: break是不必要的,因为当它进入下一个迭代时,它将脱离while循环。
startBalance = int(input("what's the stating balance? "))
balance = startBalance
numMonths = 12
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
monthlyPayment = 10
while (balance > 0):
balance = startBalance # reset the balance each iteration
print('checking monthly payment of',monthlyPayment)
for each in range(0, numMonths):
balance = balance - monthlyPayment
balance = balance + (monthlyInterestRate * balance)
# print('at month',each,'the balance is',balance)
# changed the indentation below
if (balance > 0):
monthlyPayment += 10
print('you should pay',monthlyPayment,'per month')发布于 2016-01-28 16:15:23
for each内部的for each没有意义。不需要if。我尝试使用这些更改,它与您的测试用例相匹配。
发布于 2016-01-28 16:22:19
这个怎么样:
annualInterestRate = 0.2
monthlyInterestRate = annualInterestRate / 12.0
monthlyPayment = 10
running = true;
while (running):
currentBalance = balance
for each in range(0, 12):
currentBalance = currentBalance - monthlyPayment
currentBalance = currentBalance + (monthlyInterestRate * currentBalance)
if (currentBalance > 0):
monthlyPayment += 10
else:
running = false
print monthlyPayment实际上,我所做的就是把如果-条件从每一个,与一个副本的平衡使用。运行时,本质上迭代monthlyPayment的可能值。
(如果更早地设置了currentBalance,则可以使用while(currentBalance > 0),但是我会使用自己的时间(运行)方法,这样就可以像做直到循环那样读取)
https://stackoverflow.com/questions/35066252
复制相似问题