浙大版《C语言程序设计(第3版)》题目集 习题4-11 兔子繁衍问题 (15分)

在这里插入图片描述
题解:斐波那契数列
月份:1 2 3 4 5 6 7 8 9
对数:1 1 2 3 5 8 13 21 34
为何从month = 2开始?因为斐波那契数列第0项和第1项我们已经赋值了,所以从第2项开始。

#include <stdio.h>
int main()
{
    int N, month, x1 = 1, x2 = 1, x3 = 0;
    scanf("%d", &N);
    if (N == 1) // 1对至少需要1个月。
        month = 1;
    else
        for (month = 2; x3 < N; month++)
        { // 斐波那契的迭代。
            x3 = x1 + x2;
            x1 = x2;
            x2 = x3;
        }
    printf("%d", month);
    return 0;
}
发布了165 篇原创文章 · 获赞 117 · 访问量 7799

猜你喜欢

转载自blog.csdn.net/qq_44458489/article/details/105320897