java算法练习题兔子繁殖问题(斐波那契)



java算法大全之兔子繁殖问题(斐波那契问题)。算法 题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

/*
*/

//增加了对异常的处理,输入异常的话要求重新输入,增强了健壮性

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
public class Basic1 {


public static void main(String args[])
{
Basic1  my = new Basic1();
my.count();
}

public void count()
{
int endMonth =1;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(“请输入截止月份”);
try {
endMonth = Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
//e.printStackTrace();
System.out.println(“输入月份有误,请输入数字”);
count();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int f1 = 1;//出生0-1个月内的兔子对数
int f2 = 0;//出生1-2个月内的兔子对数
int f3 = 0;//出生2-3个月内的兔子对数
int temp = 0;
for(int i =1 ;i<=endMonth;i++)
{
temp = f3;
f3 = f3 + f2;
f2 = f1;
f1 = temp;
System.out.println(“第”+i+”个月兔子对数为”+(f1+f2+f3));
}
count();

}

运行结果如下图

}