题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少? 1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21…
规律:当前这个数等于前两个数相加之和。
分析:首先利用赋值列出前四个月的兔子总数,但是第四个月可以先设为一个空值(代码中等于0因为没有空值idea在输出的时候会报错);然后4月份之后的通过for循环换值来实现,大致思想就是当前这个数等于前两个数相加之和。如果键盘输入月份小于等于3,利用switch输出兔子总数;如果键盘输入月份大于3,就在for循环计算出兔子总数之后输出。
代码:
public class ademo1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入月份:");
int month = input.nextInt();
int first = 1;
int second = 1;
int third = 2;
int fouth =0 ;
switch (month){
case 1:
System.out.println("第1个月的兔子总数为:1对");
break;
case 2:
System.out.println("第2个月的兔子总数为::1对");
break;
case 3:
System.out.println("第3个月的兔子总数为::2对");
break;
}
if (month > 3) {
int i = 4;
for (; i <= month; i++) {
fouth = third + second;
second = third;
third = fouth;
}
System.out.println("第"+(i-1)+"个月的兔子总数为:"+fouth+"对");
}
}
}