Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
编写计算斐波那契(Fibonacci)数列的第n项函数fib(n)(n < 40)。
数列描述:
f1=f2==1;
fn=fn-1+fn-2(n>=3)。
Input
输入整数 n 的值(0 < n < 40)。
Output
输出fib(n)的值。
Sample Input
7
Sample Output
13
Hint
注意第1项和第2项的输出处理
Source
这种利用已知的递推公式求之定项的题用函数的递归,便十分简单就能实现
#include <stdio.h>
#include <stdlib.h>
int f(int n)
{
if(n==1||n==2)
return 1;
//一定要有一个确定的已知前几项,以此来作为函数递归的结束标志;
else return f(n-1)+f(n-2);
//这就是题目中给出的递推公式;
}
int main()
{
int n;
scanf("%d",&n);
printf("%d\n",f(n));
return 0;
}