- 假设你每年初往银行账户中1000元钱,银行的年利率为4.7%。
一年后,你的账户余额为:
1000 * ( 1 + 0.047) = 1047 元
第二年初你又存入1000元,则两年后账户余额为:
(1047 + 1000) * ( 1 + 0.047) = 2143.209 元
以此类推,第10年年末,你的账户上有多少余额?
注:结果保留2位小数(四舍五入)。
这一题我又是想了很久才找到解决方案,差不多半小时才解决:
# -*- coding: UTF-8 -*-
"""
Created on 2017/3/16
@author: cat
假设你每年初往银行账户中1000元钱,银行的年利率为4.7%。
一年后,你的账户余额为:
1000 * ( 1 + 0.047) = 1047 元
第二年初你又存入1000元,则两年后账户余额为:
(1047 + 1000) * ( 1 + 0.047) = 2143.209 元
以此类推,第10年年末,你的账户上有多少余额?
注:结果保留2位小数(四舍五入)。
f(1) =1000*(1+u)
f(2) =(f(1)+1000) *(1+u)
...
f(n) =( f(n-1)+1000) * (1+u)
"""
def compute(base, update, years):
c_money = 0 # 当年余额
c_year = 0 # 当前是第几年
while c_year < years:
c_year += 1
c_money = (c_money + base) * (1 + update)
return (round(c_money, 2), c_year)
base = 1000
update = 0.047
print "total money and years are ", compute(base, update, 1)
print "total money and years are ", compute(base, update, 2)
print "total money and years are ", compute(base, update, 10)
total money and years are (1047.0, 1)
total money and years are (2143.21, 2)
total money and years are (12986.11, 10)
后来一想,还有更简便的方式:
def compu(base, update, years):
c_money = 0
while years > 0:
c_money = (c_money + base) * (1 + update)
years -= 1
return round(c_money,2)

本文通过一个具体的例子展示了如何使用Python计算连续多年定期存款后的总金额,包括两种不同的计算方法实现。
806

被折叠的 条评论
为什么被折叠?



