实验10-7 递归求Fabonacci数列(10 分)

实验10-7 递归求Fabonacci数列(10 分)

本题要求实现求Fabonacci数列项的函数。Fabonacci数列的定义如下:

$f(n)=f(n−2)+f(n−1) (n≥2)$,其中$f(0)=0,f(1)=1$。

函数接口定义:

1
int f( int n );

函数f应返回第n个Fabonacci数。题目保证输入输出在长整型范围内。建议用递归实现。

裁判测试程序样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>

int f( int n );

int main()
{
int n;

scanf("%d", &n);
printf("%d\n", f(n));

return 0;
}

/* 你的代码将被嵌在这里 */

输入样例:

1
6

输出样例:

1
8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>

int f( int n );

int main()
{
int n;

scanf("%d", &n);
printf("%d\n", f(n));

return 0;
}

int f(int n)
{
int result;
if (n == 0)
result = 0;
else if (n == 1)
result = 1;
else
result = f(n-2) + f(n-1);
return result;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×