一道经典编程题:
    有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
    要求用Java编写。
    请知道者为本人解决这个问题。谢谢了!

解决方案 »

  1.   

    public class Test {
        public static void main(String[] args) {
            int month = new Scanner(System.in).nextInt();
            System.out.println(getCount(month));
            // 返回第month个月共有多少对兔子
        }
        
        public static int getCount(int i) {
            return i == 1 || i == 2 ? 1 : getCount(i - 1) + getCount(i - 2);
        }
    }
    这其实是输出一个斐波那契数列 
    兔子的规律为数列1,1,2,3,5,8,13,21....这是我这个月第二次回复这个问题了,-_-!
      

  2.   

    public class Test {
        public static void main(String[] args) {
            for(int i=1;i<=10;i++)
             System.out.println("第 "+i+" 个月兔子的总对数为:"+getTotalCount(i));
        }
        
        //返回第month个月刚刚出生的兔子对数
        public static int getCount(int month) {
            return month == 1 || month == 2 ? 1 : month-1;
        }
        
        //返回第month个月兔子的总对数
        public static int getTotalCount(int month) {
         int sum =1; //第一对兔子
        
         for(int i=1;i<=month;i++)
         sum += getCount(i);
        
         return sum;
        }
    }