求第n项的斐波那契数。
1 1 2 3 5 8 ...
输入样例:
6 10
输出样例:
8
55
#include<iostream>
#include<fstream>
#include<cmath>
using namespace std;
int main()
{
ifstream cin("test.txt");//向OJ提交时,注释此句
int n;
while (cin >> n)
{
int f1 = 1;//第一项
int f2 = 1;//第二项
if (n == 1)
cout << f1 << endl;
else if (n == 2)
cout << f2 << endl;
else
{
for (int i = 3; i <= n; ++i)
{
int tmp = f1 + f2;//将前两项相加
f1 = f2;//更新第一项
f2 = tmp;//更新第二项
}
cout << f2 << endl;
}
}
system("pause");//向OJ提交时,注释此句
return 0;
}