1.使用迭代函数
#include<iostream>
#include<iomanip>
using namespace std;
void fb(int n);
int main()
{
double x;
cout << "请输入n的值:" << endl;
cin >> x;
fb(x);
return 0;
}
void fb(int x)
{
double f1 = 1, f2 = 1;
double fn = 1;
int n = 1;
while (n <= 2 && n <= x)
{
fn = 1;
if (n == x)//求到某一项即停止
{
cout << "第" << n << "项的值为:" << fn;
break;
}
n++;
}
while (n > 2 && n <= x)
{
fn = f1 + f2;
if (n == x)//求到某一项即停止
{
cout << "第" << n << "项的值为:" << fn;
break;
}
f1 = f2;//f1 f2 fn a
f2 = fn;// f1 f2 fn b
n++;//要把上面a式变成b式,为何进行左端操作一目了然
}
}
利用迭代打印出n项斐波那契数列
#include<iostream>
#include<iomanip>
using namespace std;
void fb(int n);
int main()
{
double x;
cout << "请输入n的值:" << endl;
cin >> x;
fb(x);
return 0;
}
void fb (int x)
{
double f1 = 1,f2=1;
double fn = 1;
double n = 1;
while (n <= 2&&n<=x)
{
fn = 1;
cout <<"F"<<n<<"的值为:" << fn << endl;
n++;
}
while (n > 2&&n<=x)
{
fn = f1 + f2;
cout << "F" << n << "的值为:" << fn << endl;
f1 = f2;
f2 = fn;
n++;
}
}
2.使用递归函数
#include<iostream>
#include<iomanip>
using namespace std;
double fb(int n);
int main()
{
int n;
cout << "请输入n的值:" << endl;
cin >> n;
cout << "第"<<n<<"项的值为:" << fb(n);
return 0;
}
double fb (int n)
{
if (n == 1 || n == 2)
{
return 1;
}
else if (n > 2)
{
return fb(n - 1) + fb(n - 2);
}
}
第二种就如同数学表达式一样,但运行效率没有第一种高