c++打印斐波那契数列

#include <iostream>
#include <iomanip>

using namespace std;


void PrintFibonacciSequence_1(uint16_t n)
{
    uint16_t i = 1, j = 1;

    if (1 == n) {
        cout << setw(3) << n << ',';
    }
    else if (2 == n) {
        cout << setw(3) << 1 << ',' << setw(3) << 1 << ',';
    }
    else if(3 <= n) {
        cout << setw(3) << 1 << ',' << setw(3) << 1 << ',';
        n -= 2;
        while (n-- > 0) {
            cout << setw(3) << i + j << ',';
            j += i;
            i = j - i;
        }
    }
}
void PrintFibonacciSequence_2(uint16_t n)
{
    uint16_t i = 0, j = 1;
    if (n == 0) {
        return;
    }
    cout << setw(3) << 1 << ',';
    while (--n > 0) {
        cout << setw(3) << i + j << ",";
        j += i;
        i = j - i;
    }
}
void PrintFibonacciSequence_3(uint16_t n)
{
    uint16_t i = 1, j = 0;
    while (n-- > 0) {
        j += i;
        i = j - i;
        cout << setw(3) << j << ",";
    }
}

int main(void)
{
    cout << "start" << endl << endl;

    PrintFibonacciSequence_1(10);
    cout << "\r\n--------------------------------------------------------\r\n";
    PrintFibonacciSequence_2(10);
    cout << "\r\n--------------------------------------------------------\r\n";
    PrintFibonacciSequence_3(10);

    getchar();
    system("pause");
}

结果:

猜你喜欢

转载自blog.csdn.net/u012308586/article/details/89486169
今日推荐