斐波那契数
斐波那契数列的排列是:1,1,2,3,5,8,13,21,34,55,89,144……
它后一个数等于前面两个数的和,这个数列从第三项开始,每一项都等于前两项之和。
递归:
#include<stdio.h>
#include<windows.h>
#pragma warning(disable:4996)
Fit(int n)
{
if (n <= 2){ //第一个和第二个都是1
return 1;
}
else{
return Fit(n - 2) + Fit(n - 1);
}
}
int main()
{
int n = 0;
printf("请输入:");
scanf("%d", &n);
Fit(n);
int ret = Fit(n);
printf("%d\n", ret);
system("pause");
return 0;
}
运行结果:
非递归(迭代法):
#include<stdio.h>
#include<windows.h>
#pragma warning(disable:4996)
int Fit(int n)
{
int first = 0;
int second = 1;
int third = 1;
while (n > 2){
n--;
first = second;
second = third;
third = first + second;
}
return third;
}
int main()
{
int n = 0;
printf("请输入:");
scanf("%d", &n);
Fit(n);
int ret = Fit(n);
printf("%d\n", ret);
system("pause");
return 0;
}
运行结果: