题目描述
Your objective for this question is to develop a program which will generate a fibbonacci number. The fibbonacci function is defined as such:
f(0) = 0
f(1) = 1
f(n) = f(n-1) + f(n-2)
Your program should be able to handle values of n in the range 0 to 50.
输入
Each test case consists of one integer n in a single line where 0≤n≤50. The input is terminated by -1.
输出
Print out the answer in a single line for each test case.
样例输入 Copy
3
4
5
-1
样例输出 Copy
2
3
5
来源/分类
首先想到的是递归 但递归会时间超限,自己用vs跑 需要多几分钟才能出结果

int f(int n)
{
if (n == 0) //出口
return 0;
if (n == 1)
return 1;
else
return f(n - 1) + f(n - 2);//关系
}
int main()
{
int n;
while (cin>>n)
{
if (n == -1)
break;
else
cout << f(n) << endl;
}
return 0;
}
关于递归思想 我也是看b战老师讲解懂得
递归思想 点击可以学习一下
其次就是用数组 这个特别简单了
#include<iostream>
using namespace std;
int main()
{
long long a[50],t; //注意这里要 longlong类型 int会超出
a[0] = 0; a[1] = 1;
while (cin >> t)
{
if (t == -1)
break;
else {
for (int i = 2; i <= t; i++)
a[i] = a[i - 1] + a[i - 2];
cout << a[t] << endl;
}
}
return 0;
}
