C++实现斐波那契数列
斐波那契指的是这样一个数列:0、1、1、2、3、5、8、13、21、34…
在数学上斐波那契数列以如被以递推的方法定义:
F(0)=0,F(1)=1, F(n)=F(n-1)+F(n-2)(n ≥ 2,n ∈ N*)
- 对于,斐波那契数列,还是比较好理解的:
第一种:使用变量实现
#include <iostream>
using namespace std;
void test()
{
int a = 0; // 起始值1
int b = 1; // 起始值1
while(b < 1000)
{
int tmp = a; // 定义临时变量,存储a的数据
a = b;
b = tmp + b;
cout << tmp << ",";
}
cout << endl;
}
int main(){
test();
system("pause");
return 0;
}
输出结果如下:
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987
第二种:使用vector容器实现
#include <iostream>
using namespace std;
#include <vector>
void printVector(vector<int> &v)
{
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}
void test02()
{
vector<int> v1;
v1.push_back(0);
v1.push_back(1);
int num = 0;
while(num < 15)
{
int res = v1[num] + v1[num+1];
v1.push_back(res);
num ++;
}
printVector(v1);
}
int main(){
test02();
system("pause");
return 0;
}
输出结果为
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
请按任意键继续. . .