斐波那契数列指的数列从第三项开始,每一项都等于前两项之和
源码:
#include<stdio.h>
#include<stdlib.h>
//非递归
int Fib1(int n){
if (n <= 0){
return 0;
}
if (n == 1||n==2){
return 1;
}
int a=1, b=1, c;
for (int i = 3; i <= n; i++){
c = a + b;
a = b;
b = c;
}
return b;
}
//递归
int Fib2(int n){
if (n <= 0){
return 0;
}
if (n == 1 || n == 2){
return 1;
}
return Fib2(n - 1) + Fib2(n - 2);
}
int main(){
printf("%d %d", Fib1(5), Fib2(5));
system("pause");
return 0;
}
运算结果示意图:
求第五个斐波那契数: