题目描述:
编写程序求斐波那契数列的第N项(N<40)。
数列递推公式为:
输入:
整数N的值。
输出:
输出f(n)的值。
代码一(函数递归法):
#include <stdio.h>
#include <string.h>
#include <math.h>
int f(int x);
int f(x)
{
if(x==1||x==2)
{
return 1;
}
else
{
return f(x-1)+f(x-2);
}
}
int main()
{
int a;
scanf("%d",&a);
printf("%d",f(a));
return 0;
}
用此方法,若次数运行过多时会吃力。
代码二(函数迭代法):
#include <stdio.h>
#include <stdlib.h>
int fib(n)
{
int a=1,b=1,c=1;
while(n>=3)
{
c=a+b;
a=b;
b=c;
n--;
}
return c;
}
int main()
{
int n,ret=0;
scanf("%d",&n);
ret=fib(n);
printf("%d",ret);
return 0;
}
用此方法较代码一效率提高,但若次数太大结果会表示不出来。