+ -
当前位置:首页 → 问答吧 → 【原创】该存多少钱之递归法

【原创】该存多少钱之递归法

时间:2010-09-16

来源:互联网

  1. /*  
  2. * 假设银行一年整存零取的月息为0.63%。现在某人手中有一笔钱,  
  3. * 他打算在今后的五年中的年底取出1000元,到第五年时刚好取完,  
  4. * 请算出他存钱时应存入多少?  
  5. *  
  6. * 因为按照本题有如下公式:   
  7. * 当1<=n<=4 时  
  8. *   f(n) =( f(n+1)+1000) / (1+0.0063*12)  
  9. * 当 n=5 时  
  10. *  f(n) = 1000/(1+0.0063*12)  
  11. * 所以可以采用递归的算法  
  12. */  
  13.   
  14. #include <stdio.h>   
  15. #include <assert.h>   
  16. float getTotal(int year)   
  17. {   
  18.     if(year==5)   
  19.       return 1000/(1+0.0063*12);   
  20.     else  
  21.       return  (getTotal(year+1)+1000)/(1+0.0063*12);   
  22. }   
  23. int   
  24. main(void)   
  25. {   
  26.     int i;   
  27.     float total=0;   
  28.     total = getTotal(1);        
  29.     printf("他的首次存款额最少为 %.2f ?\n",total);   
  30.       
  31.     return 0;   
  32. }  
  33. /*
  34. * 假设银行一年整存零取的月息为0.63%。现在某人手中有一笔钱,
  35. * 他打算在今后的五年中的年底取出1000元,到第五年时刚好取完,
  36. * 请算出他存钱时应存入多少?
  37. *
  38. * 因为按照本题有如下公式:
  39. * 当1<=n<=4 时
  40. *   f(n) =( f(n+1)+1000) / (1+0.0063*12)
  41. * 当 n=5 时
  42. *  f(n) = 1000/(1+0.0063*12)
  43. * 所以可以采用递归的算法
  44. */

  45. #include <stdio.h>
  46. #include <assert.h>
  47. float getTotal(int year)
  48. {
  49. if(year==5)
  50.    return 1000/(1+0.0063*12);
  51. else
  52.    return  (getTotal(year+1)+1000)/(1+0.0063*12);
  53. }
  54. int
  55. main(void)
  56. {
  57.     int i;
  58.     float total=0;
  59.     total = getTotal(1);     
  60.     printf("他的首次存款额最少为 %.2f ?\n",total);
  61.    
  62.     return 0;
  63. }
复制代码
Output:

1
他的首次存款额最少为 4039.44 元



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/asiainfolf/archive/2010/09/16/5887357.aspx

作者: sohu2000000   发布时间: 2010-09-16

看了楼主的很多小代码的例子都是递归, 楼主对递归有偏爱?

作者: zhangsuozhu   发布时间: 2010-09-16