[原創 轉載注明出處]
題目1:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子長到第三個月后每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數為多少?
思路:
第一個月兔子數為 2
第二個月兔子數不變為 2
第三個月兔子生了一對兔子 2+2=4
第四個月兔子又生了一對兔子 2+2*2=6
第五個月兔子生的兔子也開始生兔子了 2+2*3+2=10
第六個月兔子生的兩對兔子都開始生兔子了 2+2*4+2*2+2=16
第七個月兔子生的第一對兔子生的兔子也開始生兔子了 2+2*5+2*3+2+2*2+2=26
......
規律:
當月份month<3時,兔子數均為2
當月份month>3時,兔子數為 month-1月兔子數 及 month-2月兔子數 之和
Java代碼實現:
1 package jichu; 2 3 import java.util.Scanner; 4 5 public class jichu1 6 { 7 public static void main (String[] args) { 8 int num1,num2; //定義這個月和下個月兔子的數量 9 num1 = 2; //第一個月為2只 10 num2 = 2; //第二個月為2只 11 int i=1; //循環遍歷 12 int month; //月份數 13 int num3 = 0; 14 15 @SuppressWarnings("resource") 16 Scanner in = new Scanner(System.in); 17 System.out.println(" 請輸入你想要查看的月數: "); 18 month = in.nextInt(); 19 20 //打印出第一個月到輸入月份兔子的數量 21 while(i <= month) 22 { 23 num1 = num2; 24 num2 = num3; 25 num3 = num1 + num2; 26 System.out.println(" month: " + i + " num: " + num3); 27 i++; 28 } 29 } 30 }
[原創 轉載注明出處]
