尝试使用递归函数计算斐波那契数,但我的代码使用了2个递归调用。是否可以只使用一个?将n-1
的fib数保存到数组或类似物中,然后在函数末尾添加数字,这行得通吗?
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
int fib(int n) {
assert(n >= 0);
if (n > 1)
return fib(n - 1) + fib(n - 2);
else if (n == 1)
return 1;
else
return 0;
}
int main(void) {
int n,f;
printf("the nth number: ");
scanf("%d",&n);
f = fib(n);
printf("%d \n",f);
return 0;
}