Dra*_*rax 1 c recursion tail-recursion
我正在学习尾递归,在解决这个问题之前,我想对代码片段是否尾递归进行是/否的回答。
int fib_in(int n, int current, int prev) {
if (n == 1 || n == 2) { // n = 1 or 2 both gives fib number 1
return current;
}
return fib_in(n - 1, current + prev, current); // recursive call, current gets updated and new prev is the current, so were going backwards if that makes sense
}
int fib(int n) {
return fib_in(n, 1, 1); // 1 and 1 is the 2 first fib numbers so theyll be used as base cases
}
int main(void) {
int n, f;
printf("the nth number: ");
scanf("%d", &n);
// call fib function
f = fib(n);
printf("%d \n", f);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我当然认为是这样,但是在了解尾递归之前,我是根据另一个作业分配此功能的,所以我将使用一种我不知道的技术。这就是为什么我有点困惑的原因。
| 归档时间: |
|
| 查看次数: |
45 次 |
| 最近记录: |