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

 

程序分析:兔子的规律为数列1,1,2,3,5,8,13,21....即从第三个月起,本月的兔子数量为前两个月的兔子数量之和(此处单位为对)

package com.mxh.test;

public class Demo {
    public static void main(String[] args) {
        //上上个月兔子的数量
        int lastLastMonth=1;
        //上个月兔子的数量
        int lastMonth=1;
        //本月兔子的数量
        int thisMonth=0;
        //月份可自行改,根据自己情况改,1到12依次代表每个月份
        for (int i=1;i<=12;i++){
            if (i<=2){
                System.out.println(i+"月份有"+lastMonth+"对兔子");
            }else {
                thisMonth=lastLastMonth+lastMonth;
                //用中间变量接受
                int n=lastMonth;
                lastMonth=thisMonth;
                lastLastMonth=n;
                System.out.println(i+"月份有"+thisMonth+"对兔子");

            }

        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值