1. 程式人生 > >假設你每年初往銀行賬戶中1000元錢,銀行的年利率為4.7%。 一年後,你的賬戶餘額為: 1000 * ( 1 + 0.047) = 1047 元 第二年初你又存入1000元,則兩年後賬戶餘額為: (

假設你每年初往銀行賬戶中1000元錢,銀行的年利率為4.7%。 一年後,你的賬戶餘額為: 1000 * ( 1 + 0.047) = 1047 元 第二年初你又存入1000元,則兩年後賬戶餘額為: (

  • 假設你每年初往銀行賬戶中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)

print

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)