Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C/C++ หาลำดับฟีบอนัชชีตัวที่ n


ลำดับฟีบอนัชชี (Fibonacci) คืออนุกรมที่ตัวถัดไป = ผลรวม 2 ตัวก่อนหน้า ตัวแรกคือ 0 ตามด้วย 1

โจทย์: หาตัวที่ n ในอนุกรมฟีบอนัชชี คำนวณทุกตัวและพิมพ์ n ตัวแรก

Input: 8 Output: 0 1 1 2 3 5 8 13

คำอธิบาย

0+1=1, 1+1=2, 1+2=3, 2+3=5...

ใช้ For Loop บวก 2 ตัวก่อนหน้าเพื่อหาตัวถัดไป

ตัวอย่าง

#include <iostream>
using namespace std;
int main() {
    int t1 = 0, t2 = 1, n, i, nextTerm;
    n = 8;
    for (i = 1; i <= n; ++i) {
        if (i == 1) {
            cout << " " << t1;
            continue;
        }
        if (i == 2) {
            cout << " " << t2 << " ";
            continue;
        }
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        cout << nextTerm << " ";
    }
}

ผลลัพธ์

0 1 1 2 3 5 8 13