介绍
在本实验中,你将学习如何编写一个 C++ 程序来生成斐波那契数列,直到给定的项数。斐波那契数列是一个数字序列,其中每个数字都是前两个数字的和。在本实验中,我们将使用 for 循环来生成用户输入的给定项数的斐波那契数列。
在本实验中,你将学习如何编写一个 C++ 程序来生成斐波那契数列,直到给定的项数。斐波那契数列是一个数字序列,其中每个数字都是前两个数字的和。在本实验中,我们将使用 for 循环来生成用户输入的给定项数的斐波那契数列。
在 main.cpp
文件中,插入以下代码以包含必要的库。
#include<iostream>
using namespace std;
声明程序所需的必要变量,包括 n
、t1
、t2
和 nextTerm
。
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 循环生成数列,以及如何在终端中编译和运行程序。