百万富翁 练习

假设你月收入是3000,除开平时花销,每一个月留下1000块钱进行投资。
而后你认真的钻研了 《股票和基金 21天从入门到精通》,达到了每一年20%的投资回报率。
那么问题来了,以每一个月投资1000块钱的节奏,持续投资多少年,总收入达到100万
(复利计算按照每一年12000投入计算,不按照每个月计息)

复利公式:
F = p* ( (1+r)^n );
F 最终收入
p 本金
r 年利率
n 存了多少年

假设情景一:
p = 10000
r = 0.05
n = 1

解读:
本金是10000
年利率是5%
存了一年 1次
复利收入 10000*( (1+0.05)^1 ) = 10500

假设情景二:
p = 10000
r = 0.05
n = 2

解读:
本金是10000
年利率是5%
存了两年
复利收入 10000*( (1+0.05)^2 ) = 11025

程序:
  int fundPerMonth = 1000;//每一个月投1000元
  int fundPerYear = fundPerMonth * 12;//每一年投12000元
  float rate = 0.2f;//年利率
  int sum = 0;//累计收入
  int target = 1000 * 1000;//目标
  //F = p * ( 1 + r )^n;
  for(int j = 1 ; j < 100 ; j++)
  {
   int year = j;
   float compoundInterestRate = 1;
   for(int i = 0 ; i < year ; i++)
   {
    compoundInterestRate = compoundInterestRate * (1 + rate);//复利利率
   }
   int compoundInterest = (int) (fundPerYear * compoundInterestRate);//复利
   System.out.println("通过" + year + " 年,本金是"+fundPerYear+" 获得的复利收益 " + compoundInterest);
   sum += compoundInterest;
   if(sum >= target)
   {
    System.out.println("一共须要" + year + "年,累计收入超过" + target);
    break;
   }
  }

总结:这道题主要要注意:每一年都须要投入12000元,因此必须将每一年投入产生的复利收益累加