3.5 斐波那契数
求第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; }
總結