首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算一年内最低月信用卡还款数的代码

计算一年内最低月信用卡还款数的代码
EN

Stack Overflow用户
提问于 2016-01-28 16:03:09
回答 4查看 2K关注 0票数 4

请让我找出我的推理有什么问题,因此我的结果。我正在学习一门在线课程,在这门课程中,我应该计算出在12个月内消除信用卡债务所需的最低数额。我得到了一个年利率,一个债务数额(余额)的价值,以及一个每月付款应该增加的价值(10倍)。根据我的推理,我生成的代码应该在几个月内迭代,但是如果余额不是零,它应该会增加月付款并重新计算。我的数值(我认为)与预期的结果相差很小。我的代码是这样的:

代码语言:javascript
复制
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)。

有人能帮我指点我哪里错了吗?

谢谢!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-01-28 16:46:56

你快到了。在您的实现中存在一些问题。

首先,你需要重新设置余额后,意识到之前测试的每月付款没有,嗯,支付。

其次,检查余额并增加余额的选项卡是错误的。就目前情况而言,你每月多付10美元,如果我正确理解你的问题,这不是你想要的。你想增加每月付款后,看到一个10美元,但没有支付它在12个月。

作为另一点,您的else: break是不必要的,因为当它进入下一个迭代时,它将脱离while循环。

代码语言:javascript
复制
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')
票数 2
EN

Stack Overflow用户

发布于 2016-01-28 16:15:23

  1. 全年的余额应该是相同的,因此for each内部的for each没有意义。不需要if
  2. 当尝试新的每月付款时,需要将余额重置为起始值。

我尝试使用这些更改,它与您的测试用例相匹配。

票数 1
EN

Stack Overflow用户

发布于 2016-01-28 16:22:19

这个怎么样:

代码语言:javascript
复制
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),但是我会使用自己的时间(运行)方法,这样就可以像做直到循环那样读取)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35066252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档