A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 轩辕邵宇 中级黑马   /  2014-11-17 23:16  /  1089 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子对数为多少?

6 个回复

倒序浏览
这个……
回复 使用道具 举报
class New1
{
        public static void main(String[]sgrs)
        {
                System.out.println(duiShu(10));
        }

        //定义一个duiShu方法,用来计算每月的对数。
        public static int duiShu(int n)
        {
                /*
                从兔子的前几个月对数分析规律。
                前两个月都为1.
                从第三月起,每月的对数等于该月的前两个月的对数和。
                所以有该月的对数=其前两个月的对数和,duiShu(n)==duiShu(n-1)+duiShu(n-2);
                */
                if(n==1||n==2)
                {
                        return 1;
                }else
                {
                        return duiShu(n-1)+duiShu(n-2);
                }
        }
}
回复 使用道具 举报
王立腾 发表于 2014-11-17 23:47
class New1
{
        public static void main(String[]sgrs)

腾哥哥   太用功了把   
回复 使用道具 举报
轩辕邵宇 发表于 2014-11-17 23:48
腾哥哥   太用功了把

你在逗我{:3_46:}
回复 使用道具 举报
其实就是一个斐波那契数列,可以使用递归计算
  1. public class Test1 {
  2.         public static void main(String[] args) {
  3.                 System.out.println(getRabbit(12));
  4.         }
  5.         public static int getRabbit(int num){
  6.                 if(num == 1)
  7.                         return 1;
  8.                 if(num == 2)
  9.                         return 1;
  10.                 return getRabbit(num-1)+getRabbit(num-2);
  11.         }
  12. }
复制代码


回复 使用道具 举报
1.public class TestOne {   
2.  
3.    public static void main(String[] args) {   
4.        int rabbitNum = 1;   
5.        for(int i = 1 ; i < 20 ; i++){   
6.            rabbitNum = getMonthNum(i);   
7.            System.out.println("兔子第   "+i+"  个月的总数为:"+rabbitNum);   
8.        }   
9.           
10.    }   
11.      
12.    public static int getMonthNum(int x){   
13.        int initRabbit = 1;   
14.           
15.        if(x == 1 || x == 2){   
16.            return initRabbit;   
17.        }   
18.           
19.        initRabbit = getMonthNum(x-1) + getMonthNum(x-2);   
20.           
21.        return initRabbit;   
22.    }   
23.}  
//我也找的 还在学基础  希望帮到你
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马