【问题标题】:Yearly Interest on house and deposit房屋和存款的年利息
【发布时间】:2019-12-14 21:46:53
【问题描述】:

假设您目前有 50,000 美元存入银行账户,并且该账户以每年 3.5% 的固定利率支付您的存款。您正计划以 300,000 美元的当前价格购买一栋房屋。价格将每年上涨 1.5%。它仍然需要最低首付为房价的 20%。

编写一个while循环来计算您需要等待多少(整数)年才能负担得起买房的首付。

m = 50000 #money you have
i = 0.035 #interest rate
h = 300000 #house price
f = 0.015 #amount house will increase by per year
d= 0.2 #percent of down payment on house
y = 0 #number of years
x = 0 #money for the down payment

mn = h*d #amount of down payment

while m <= mn:
   m = (m+(m*i)) #money you have plus money you have times interest
   y = y + 1 #year plus one
   mn = mn +(h*f*y)

print(int(y))

你应该得到的答案是 10。

我一直得到错误的答案,但我不确定什么是错误的。

【问题讨论】:

  • 想想你是如何计算房子的价值的。当您计算您的储蓄利息时,您使用了上一年的价值并将利息添加到其中。尝试重写 mn 行,使其看起来更像 m 行。
  • 成功了!谢谢。while m &lt;= mn: m = (m+(m*i)) #money you have plus money you have times interest y = y + 1 #year plus one mn = mn +(mn*f)

标签: python python-3.x while-loop


【解决方案1】:

您可以使用复利公式简化代码。

def compound_interest(amount, rate, years):
    return amount * (rate + 1) ** years


while compound_interest(m, i, y) < d * compound_interest(h, f, y):
    y += 1

如果允许不使用while循环,则可以在y之后解决不等式。

所以你得到这个代码sn-p:

import math

base = (i + 1) / (f + 1)
arg = (d * h) / m
y = math.ceil(math.log(arg, base))

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 2014-08-30
    • 2018-09-20
    相关资源
    最近更新 更多