首页 > 学院 > 开发设计 > 正文

我的学习笔记之兔子的只数

2019-11-06 06:55:50
字体:
来源:转载
供稿:网友

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

问题分析: 第一个月和第二个月的兔子只数是一对,第三个月的兔子是两对,第四个月的只数是三对……依次类推可以获取到兔子对数的变化为:1,1,2,3,5,8,13,21,34…… 从上述数字中可以观察到的规律是从第三个月开始,兔子的对数是前两个月的兔子的对数之和。 代码如下:

import java.util.Scanner;class Rabbit{ public static void main(String[] args) { while (true) { Scanner sc = new Scanner(System.in); System.out.PRintln("Please input the number of month:"); int num = sc.nextInt(); System.out.println("The number of rabbit is " + getNumber(num)); } } public static int getNumber(int n) { if (n == 1 || n == 2) { return 1; } else { return getNumber(n - 1) + getNumber(n - 2); } } }

运用一个方法来完成加法运算,直到把所有的兔子的对数加起来完成问题。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表