假设您目前有$ 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。
我一直得到错误的答案,但是我不确定什么是错误的。
最佳答案
您可以使用复利公式简化代码。
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
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
print(y)
如果允许您不使用while循环,则可以解决
y
年之后的不等式。因此,您将获得以下代码片段:
import math
base = (i + 1) / (f + 1)
arg = (d * h) / m
y = math.log(arg, base)
print(math.ceil(y))
关于python - 房屋和存款的年利息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59339435/