用 C++ 编写斐波那契数列程序

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习如何编写一个 C++ 程序来生成斐波那契数列,直到给定的项数。斐波那契数列是一个数字序列,其中每个数字都是前两个数字的和。在本实验中,我们将使用 for 循环来生成用户输入的给定项数的斐波那契数列。

包含必要的库

main.cpp 文件中,插入以下代码以包含必要的库。

#include<iostream>
using namespace std;

声明变量

声明程序所需的必要变量,包括 nt1t2nextTerm

int n, t1=0, t2=1, nextTerm=0;

获取项数

从用户处获取项数并将其存储在变量 n 中。

cout << "Enter the number of terms: ";
cin >> n;

生成斐波那契数列

使用 for 循环生成斐波那契数列,直到给定的项数。

cout << "Fibonacci Series: ";
        for (int 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 << " ";
        }

编译并运行程序

要编译程序,请打开终端并导航到 ~/project 目录。输入以下命令:

g++ main.cpp -o main && ./main

如果程序没有错误,它将成功编译并运行。

输出

输入你想要生成的斐波那契数列的项数,程序将打印出该数列。
例如:

Enter the number of terms: 7
Fibonacci Series: 0 1 1 2 3 5 8

完整代码

以下是 main.cpp 文件的完整代码。

#include<iostream>
using namespace std;

int main()
{
    int n, t1=0, t2=1, nextTerm=0;

    cout << "Enter the number of terms: ";
    cin >> n;
    cout << "Fibonacci Series: ";

    for (int 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 << " ";
    }

    return 0 ;
}

总结

在本实验中,你学习了如何编写一个 C++ 程序来生成斐波那契数列,直到给定的项数。程序从用户处获取项数作为输入,并打印出斐波那契数列。你还学习了如何使用 for 循环生成数列,以及如何在终端中编译和运行程序。

您可能感兴趣的其他 C++ 教程