古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,
小兔子長到第三個月后每個月又生一對兔子,假如兔子都不死,
問每個月的兔子總數為多少?
程序分析:兔子的規律為數列1,1,2,3,5,8,13,21....
public class 第一題兔子問題 { public static void main(String[] args) { System.out.print("請輸入月份:"); Scanner in = new Scanner(System.in); int n = in.nextInt(); int total = 0; //記錄耗子總數
int y = 2; //記錄老耗子
int x1 = 0; //記錄滿一個月的耗子
int x2 = 0; //記錄滿兩個月的耗子
int x3 = 0; //記錄滿三個月的耗子
for(int i=0; i<n; i++) { y += x3; //新的老耗子數量 = 老耗子 + 滿三個月的耗子
x3 = x2; x2 = x1; x1 = y; } total = y + x1 + x2 + x3; System.out.println(n + "個月后的耗子數量為" + total + "只"); in.close(); } }