关于java:Java编程练习题

2次阅读

共计 510 个字符,预计需要花费 2 分钟才能阅读完成。

程序 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;
        }
    }
}

正文完
 0