文章

1

粉丝

132

获赞

0

访问

2.3k

头像
(非题解,仅记录代码)迭代 + 循环
P1275 上海交通大学机试题
发布于2023年1月16日 23:26
阅读数 2.3k

迭代法 

#include <iostream>

using namespace std;

int main() {
    // F0 = 0
    int a = 0;
    // F1 = 1
    int b = 1;
    int n;
    // current 为 Fn对应的值,初始为F0,即a
    int current = a;
    cin >> n;
    // 开始迭代
    for (int i = 0; i < n; i++) {
        // current 为 Fi 的值
        int currnet = a;
        a = b;
        b = currnet + b;
    }
    cout << a;
}

递归法

#include <iostream>

using namespace std;

int Fibonacci(int n) {
    if ( n == 0 ) return 0;
    if ( n == 1 ) return 1;
    return Fibonacci(n-1) + Fibonacci(n-2);

}

int main() {
    int n;
    cin >> n;
    cout << Fibonacci(n);

}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发