#include<stdio.h>
#include<stdlib.h>
//递归求法
int fib(int n) {
if (n == 1)
return 1;
if (n == 2)
return 1;
return (fib(n - 1) + fib(n - 2));
}
int main() {
printf("%d\n", fib(n));
system("pause");
return 0;
}n
//非递归求法
int Fib(int n){
if (n < 1)
return 0;
else if (n == 1 || n == 2)
return 1;
int res = 1;
int pre = 1;
int temp = 0;
for (int a = 3; a <= n; a++) {
temp = res;
res = pre + res;
pre = temp;
}
return res;
}
int main() {
printf("%d\n", Fib(n));
system("pause");
return 0;
}
C 递归和非递归分别实现求第n个斐波那契数。
最新推荐文章于 2024-07-22 20:42:16 发布