用C语言编写程序.求fibonacci数列的第9项

2024-12-05 08:03:05
推荐回答(3个)
回答1:

用递归

#include
int fibonaci(int n) //求数列第n项的函数
{
int a;
if(n==0)return 0; //定义第0项为0
else if(n==1) return 1; //第一项为1
else
{
a=fibonaci(n-1)+fibonaci(n-2); //前两项和
}
return a;
}
main()
{
printf("%d",fibonaci(9)); //输出第9项
}

回答2:

#include

int main()
{
int F[10]={0,1,1};
int i;
for(i=2;i<=9;i++)
{
F[i]=F[i-1]+F[i-2];
}
printf("%d\n",F[9]);
return 0;
}

回答3:

#include

#define Nth 9

int main()
{
int i;
int fib_m, fib_n, fib;

fib_m = 0; /* the first number is 0 */
fib_n = 1; /* the 2nd one is 1 */
fib = (Nth==2?fib_n:fib_m); /* set correct fib in case Nth is 1 or 2 */

for (i = 3; i <= Nth; i++)
{
fib = fib_m+fib_n;
fib_m = fib_n;
fib_n = fib;
}

printf("The %dth fibonacci number is %d\n", Nth, fib);
return 0;
}