兔子数量问题(斐波那契数列)
题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21....
package com.likunjie; import java.util.Scanner; public class RabbitTest { //此题也是斐波那契 数列题目 public static void main(String[] args) { while (true) { int a = 1, b = 1; int temp = 0; Scanner scan = new Scanner(System.in); System.out.print("Please input a number: "); int months = scan.nextInt(); if (months == 1 || months == 2) { System.out.println("There's " + 1 + " couple of rabbit in total."); } else if (months > 2) { for (int i = 3; i <= months; i++) { temp = b; b = a + b; a = temp; System.out.println("第" + i + "个月的兔子数是:" + b); } } else{ System.out.println("Wrong Error....System exit...."); break; } } } }