本题要求实现一个递归函数int fib(int n),返回斐波那契数列的第n项。例如如果n=5,则该函数应该返回5。
注:该数列的前面几项是: 1 1 2 3 5 8 13 21 34 ...
函数接口定义:
int fib(int n);
其中 n
的值不超过1<=n<=46
。
裁判测试程序样例:
#include <stdio.h>
/* 请在这里填写答案 */
int main(int argc, char const *argv[])
{
int n;
while (scanf("%d", &n) != EOF) {
printf("%d\n", fib(n));
}
return 0;
}
输入样例:
5
输出样例:
5
本题哪里有问题我特不知道,只能这么写。
int fib(int n)
{
if(n==1) return 1;
else if(n==2) return 1;
else if(n==3) return 2;
else if(n==4) return 3;
else if(n==5) return 5;
else if(n==6) return 8;
else if(n==7) return 13;
else if(n==8) return 21;
else if(n==9) return 34;
else if(n==10) return 55;
else if(n==11) return 89;
else if(n<=46) return fib(n-1)+fib(n-2);
}