【斐波那契数列】兔子繁殖

问题描述:

有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月 后每个月又生一对兔子,假如兔子都不死,请输出前20个月的每个月的兔子数量。

思路解析:

代码:

#include<iostream>
using namespace std;
int geshu(int month) {
    if (month < 1) {
        cout << "输入错误!" << endl;
        return 0;
    }else if (month == 1 || month == 2){
        return 1;
    }else if (month > 2) {
        int temp[100];
        temp[0] = temp[1] = 1;
        //每调用一次递归,就要从头重新计算一次值,效率太低,重复性太高。
        //通过for循环,将值存储到数组中,这样可以减少递归的调用次数,提高代码效率。
        for (int i = 2; i < month; i++) {
            temp[i] = temp[i - 1] + temp[i - 2];
        }
        return temp[month - 1];
    }
}
int main() {
    for (int i = 1; i <= 20; i++) {
        cout <<geshu(i) << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_59942266/article/details/129271205