斐波那契数列规律是从第三个数开始每个数是前两个数的和 递归:
#include <stdio.h>
int Fibon(int n)
{
if (n < 0)
{
printf("n is error!\n");
return -1;
}
else if(n<2)
return n == 0? 0:1;
else if(n>=2)
return Fibon(n-1) + Fibon(n-2);
}
int main()
{
int n;
print("输入查询的第几个数")
scanf("%s",n);
print("斐波那契数列第%d项为:%d",n,Fibon(n))
}
非递归
#include <stdio.h>
int Fibon(int n)
{
if (n < 0)
{
printf("n is error!\n");
return -1;
}
int n1 = 1;
int n2 = 2;
int n3 = 3;
for (int i = 3;i <= n;++i)
{
n3 = n1+n2;
n1 = n2;
n2 = n3;
}
return n3;
}
int main()
{
int n;
print("Please input Fibon index:")
scanf("%s",n);
print("斐波那契数列第%d项为:%d",n,Fibon(n))
}
|