.有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一 对兔子,假如兔子都不死,问每个月的兔子总数为多少? 1.程序分析: 兔子的规律为数列1,1,2,3,5,8,....;求Java程序代码
a[i]=a[i-1]+a[i-2]就行了呗,java难道难写吗
public class Test {
public static void main(String[] arg0){
Scanner sc = null;
while (true){
sc = new Scanner(System.in);
int month = sc.nextInt();
System.out.println("兔子数为" + numOfRabbit(month) + "只");
}
}
private static int numOfRabbit(int month) {
if(month == 1 || month == 2)
return 1;
else return numOfRabbit(month - 1) + numOfRabbit(month - 2);
}
}
可以参看本人的一篇博客,提供了递归和非递归两种实现方法及效率对比。