int Fb1(int i)
{
int x1, x2, an, n;
x1 = 0;
x2 = 1;
an = 1;
n = 1;
while (n < i)
{
n++;
an = x1 + x2;
x1 = x2;
x2 = an;
}
return an;
}
首先是循环法。
int Fb2(int n)
{
if((n == 1)||(n == 2))
{
return 1;
}
else
{
return (Fb2(n - 1) + Fb2(n - 2));
}
}
然后是递归函数法。
#include <stdio.h>
#include <stdlib.h>
int Fb1(int i);
int Fb2(int n);
int main()
{
int n;
int x1, x2;
scanf("%d", &n);
x1 = Fb1(n);
x2 = Fb2(n);
printf ("%d\n%d", x1, x2);
return 0;
}
int Fb1(int i)
{
int x1, x2, an, n;
x1 = 0;
x2 = 1;
an = 1;
n = 1;
while (n < i)
{
n++;
an = x1 + x2;
x1 = x2;
x2 = an;
}
return an;
}
int Fb2(int n)
{
if((n == 1)||(n == 2))
{
return 1;
}
else
{
return (Fb2(n - 1) + Fb2(n - 2));
}
}
全部代码如上。
|