题目: 有一对兔子,从出生后第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); } } }运用一个方法来完成加法运算,直到把所有的兔子的对数加起来完成问题。
新闻热点
疑难解答