求第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;}
新聞熱點
疑難解答