技术,瞎侃,健康,休闲……

mahu@cppblog 人类的全部才能无非是时间和耐心的混合物
posts - 11, comments - 13, trackbacks - 0, articles - 12
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Fibonacci Freeze

Posted on 2006-06-10 01:10 mahudu@cppblog 阅读(333) 评论(0)  编辑 收藏 引用 所属分类: C/C++

The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) are defined by the recurrence:

eqnarray20

Write a program to calculate the Fibonacci Numbers.

Input and Output

The input to your program would be a sequence of numbers smaller or equal than 5000, each on a separate line, specifying which Fibonacci number to calculate.

Your program should output the Fibonacci number for each input value, one per line.

Sample Input

5
7
11

Sample Output

The Fibonacci number for 5 is 5
The Fibonacci number for 7 is 13
The Fibonacci number for 11 is 89

Solution

#include <iostream>

using namespace std;

 

int main()

{

   int first,next,temp,n;

   while(cin >> n) {

      first = 0;

      next = 1;

      temp = 0;

      if(n == 0 || n == 1) {

        cout << "The Fibonacci number for" << " " << n << " " << "is" << " " << n << endl;

      }

      else {

        for(inti = 2; i <= n; i++) {

           temp = first + next;

           first = next;

           next = temp;

        }

        cout << "The Fibonacci number for" << " " << n << " " << "is" << " " << temp << endl;

      }

   }

   return 0;

}


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理