如何用C语言编写函数实现用递归法求Fibonacci数列前n项的值, n的值由键盘输入?

2024-10-29 08:44:43
推荐回答(3个)
回答1:

设此所求的数列为:0,1,1,2,3,5,8,13,21,……(n=0,1,2,3,……)

#include

long Fibonacci(int n)

{

if(n==0||n==1)

return (long)n;

else

return Fibonacci(n-1)+Fibonacci(n-2);

}

int main()

{

    int n;

scanf("%d",&n);

printf("F(%d)=%ld\n",n,Fibonacci(n));

getch();

    return 0;

}

回答2:

#include "stdio.h"
int fab(int n)
{
if(n==1||n==2) return 1;
else return fab(n-1)+fab(n-2);
}
void main()
{
int a,i;
printf("请输入个整数:");
scanf("%d",&a);
for(i=1;i<=a;i++)
printf("%d ",fab(i));}

回答3:

#include "stdio.h"
int Fibonacci(int a)
{
int sum;
if((a==1)||(a==2))
{
return 1;
}
else
{
sum = Fibonacci(a-1)+Fibonacci(a-2);
}
return sum;
}void main()
{
int n;
int sum;
printf("input n,n>3:");
scanf("%d",&n);
if(n<1)
{
printf("input error");
}
sum=Fibonacci(n);
printf("%d\n",sum);
}