关于java:Java编程练习题

程序1

古典问题:有一对兔子,从出世后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,如果兔子都不死,问每个月的兔子对数为多少?
剖析:1月-1对 2月-1对 3月-2对 4月-3对 5月-5对 6月-8对 7月-13对
以后月的对数是前两个月的和(除了1、2月)

public class TestTime {
    public static void main(String[] args) {

        //创立一个规范输出流
        Scanner in = new Scanner(System.in);
        System.out.print("请输出月份:");
        int month = in.nextInt();
        System.out.println("以后月份的数量是:" + getNumByMonth(month));
    }

    /**实现*/
    public static Integer getNumByMonth(Integer month){
        Integer num = 0;
        if (month == 1 || month == 2){
            num = 1;
            return num;
        }else {
            num = getNumByMonth(month-1) + getNumByMonth(month-2);
            return num;
        }
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理