3.5 斐波那契数
求第n項(xiàng)的斐波那契數(shù)。
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提交時(shí),注釋此句int n;while (cin >> n){int f1 = 1;//第一項(xiàng)int f2 = 1;//第二項(xiàng)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;//將前兩項(xiàng)相加f1 = f2;//更新第一項(xiàng)f2 = tmp;//更新第二項(xiàng)}cout << f2 << endl;}}system("pause");//向OJ提交時(shí),注釋此句return 0; }
總結(jié)