练习题1


package Prog_50;
/*
* 题目:
* 有一对兔子,从出生后第3个月起每个月都生一对兔子,
* 小兔子长到第三个月后每个月又生一对兔子,
* 假如兔子都不死,问每个月的兔子对数为多少? 
* 
* 规律:
* 第几个月:     1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
* 兔子的对数:     1, 1, 2, 3, 5, 8,13,21,33, 55, 89,144,233,377,
* 
*/
public class Prog1 {
  public static void main(String[] args){
    int x=5;
    //方法1
    System.out.println("第"+x+"个月兔子的对数:"+y(x));
    //方法2
    yy(5);
  }
  /*
  * y1, y2, y3, y4, y5,    y(x)
  * 1, 1,y1+y2,y2+y3,y3+y4,y(x-2)+y(x-1),
  *  
  * 当月份小于或等于2时,兔子的对数为1。
  * 设x表示月份,y(x)表示当月数量,即为(x-2)上上个月,(x-1)上个月
  * y(x-2)+y(x-1)就是x个月的数量。
  * 即y(x)=y(x-2)+y(x-1);且x<=2时,y(x)=1,
  * 
  */
  static int y(int x){
    if(x<=2){
      return 1;
    }
    return y(x-2)+y(x-1);
  } 
  static void yy(int xx){
    int y1=1;
    int y2=1;
    for(int x=1;x<=xx;x++){
      System.out.println("第"+x+"个月兔子的对数:"+y1);
      y2=y1+y2;
      y1=y2-y1;
    }
  }
}

 

posted @ 2015-12-27 17:24  唱一些温暖  阅读(179)  评论(0编辑  收藏  举报