题四:一对兔子生兔子,给个月份算有几只兔子

这个用递归就行,兔子就是个类,他们有自己的行为,这样一想就很好实现了。

/**
 * 有一对兔子,从出生后第三个月起每个月都生一对兔子,小兔子长到第三个月又生一对兔子,加入兔子都不死,问每个月的兔子总数多少?
 */
public class Test4 {
    public static void main(String[] args) {
        RabbitPair rabbitPair = new RabbitPair(6);
        System.out.println(rabbitPair.getPairCount()*2);
    }

}

class RabbitPair{
    int month;
    public RabbitPair(int month){
        this.month = month;
    }

    public int getPairCount(){
        if(month<3){
            return 1;
        }else{
            return month-2+(new RabbitPair(month-2)).getPairCount();
        }

    }
}

猜你喜欢

转载自www.cnblogs.com/flying607/p/9004158.html