Posted on 2006-06-10 01:10
mahudu@cppblog 阅读(328)
评论(0) 编辑 收藏 引用 所属分类:
C/C++
The Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...) are defined by the recurrence:
Write a program to calculate the Fibonacci Numbers.
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.
5
7
11
The Fibonacci number for 5 is 5
The Fibonacci number for 7 is 13
The Fibonacci number for 11 is 89
#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;
}