古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?

分析:

month 1 2 3 4 5 6 7 8 9 10
total 1 1 2 3 5 8 13 21 34 55

此问题是Fibonacci数列问题, f(n) = f(n-1) + f(n-2)

解决举例

package sloveproblems;

public class howmanyrabbits {

    public static void main(String[] args){
    int a = 0;
    int b = 1;
    for (int i=0; i<=9; i++){  //for ten month
        int c = a + b;
        a = b;
        b = c;
        int month = i+1;
        System.out.println("the " + month+"th rabbits are: " + a);
    }
    }
}

老齐Py
957 声望290 粉丝