1. 程式人生 > 其它 >java題目 統計每個月兔子的總數

java題目 統計每個月兔子的總數

有一隻兔子,從出生後第3個月起每個月都生一隻兔子,小兔子長到第三個月後每個月又生一隻兔子,假如兔子都不死,問第n個月的兔子總數為多少? 本題有多組資料。 資料範圍:每組輸入滿足1 \le n \le 31 \1n31

輸入描述:

多行輸入,一行輸入一個int型整數表示第n個月

輸出描述:

每一行輸出對應的兔子總數

示例1

輸入:
1
2
3
4
5
9
輸出:
1
1
2
3
5
34
 1 import java.io.BufferedReader;
 2 import java.io.InputStreamReader;
 3 import java.io.IOException;
 4 
 5 public class Main {
 6     public static void main(String[] args) throws
IOException { 7 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 8 String line; 9 while((line = br.readLine()) != null) { 10 int n = Integer.parseInt(line); 11 int mount1 = 1; //1月兔子 12 int mount2 = 0; //2月兔子 13 int
mount3 =0; //3月兔子 14 int add = 0; //下個月將出生的兔子 15 for(int i = 2; i <= n; i++) { //從2月開始計算,i表示第i個月 16 mount3 = mount3 + mount2; 17 mount2 = mount1; 18 mount1 = add; 19 add = mount2 + mount3; 20 } 21 System.out.println(mount1 + mount2 + mount3);
22 } 23 } 24 }