C编程递归

标签 c visual-studio recursion


我今天在学习 C,我碰到了这个使用递归调用的例子,但我不明白它是如何工作的。谁能解释一下?

#include <stdio.h> 
#define SIZE 10 

int sample(const int b[], int p); //function prototype

void main(void){
    int x; 

    int a[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    x = sample(a, SIZE); //call

    printf("Result is X: %d\n", x);
}

int sample(const int b[], int p){
    if (p == 1){
        return b[0];
    }
    else{
        return b[p - 1] + sample(b, p - 1); //recursive calls until p is 1
    }
}

我的问题是:为什么输出是 55? x 是否保存前一个值,然后在下一次调用示例时添加下一个值?为什么 x 的值不只是 b[0] 即 1?

最佳答案

在第一次调用 sample 时写出 p 值的表格可能会有帮助:

p          b[p - 1]
--------   --------
SIZE       10

由于 p 不是 1,函数 sample 返回计算:

b[SIZE - 1] + sample(b, SIZE - 1)

或者:

10 + sample(b, SIZE - 1)

为了计算sample(b, SIZE - 1),我们在表中写下下一个值:

p          b[p - 1]
--------   --------
SIZE - 1   9

同样,p 不是 1,因此我们最终返回以下值:

(10 + (9 + sample (b, (SIZE - 1) - 1)))

如果你重复这些步骤,你可以看到这最终是如何终止的,因为我们到达了 p1 的状态:

(10 + (9 + (8 + ... + (1)))

这导致答案 55

关于C编程递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25854965/

相关文章:

php - 实例化 : what should happen at low level

检查c中数组中的值

c - 线程为 "suspended"对 POSIX 意味着什么?

c++ - 包括 C++ 源文件是一种批准的方法吗?

javascript - 如何递归迭代 JS 对象,同时创建具有类似结构的新对象?

c - 也许是指针问题。 Linux程序+libpcap+getopt_long()+C语言

c# - 软件包与 netcoreapp2.0 不兼容

c++ - 调试 "crashed"最上面的窗口

algorithm - Avoidland - 放置 n 个棋子的最小步数,以便每行和每列中只有一个?

python - 从迭代到递归 - 重新排序列表