繁体   English   中英

如何理解大输入的递归函数调用

[英]How to understand a recursive function call for large inputs

以下代码的结果是 0,1,2,0,每次调用都明确写完后我完全理解。 但是我想知道是否有更简单的方法来理解递归函数想要实现的内容并更快地找到结果? 我的意思是如果 a=1000 我们不能写所有的电话。

#include<stdio.h>
void fun(int);
typedef int (*pf) (int, int);
int proc(pf, int, int);

 int main()
{
int a=3;
fun(a);
return 0;
}
void fun(int n)
{
     if(n > 0)
    {
         fun(--n);
         printf("%d,", n);
         fun(--n);
    }
}

您需要做的就是添加一些调试语句以更好地理解它。 这是我添加来跟踪它的 if 语句的结果:

start program
before if, n is = 3
before fun call, n is = 3
before if, n is = 2
before fun call, n is = 2
before if, n is = 1
before fun call, n is = 1
before if, n is = 0
printing = 0
before if, n is = -1
after second fun call, n is = -1
printing = 1
before if, n is = 0
after second fun call, n is = 0
printing = 2
before if, n is = 1
before fun call, n is = 1
before if, n is = 0
printing = 0
before if, n is = -1
after second fun call, n is = -1
after second fun call, n is = 1
end program

你的问题不是“这是做什么的?” 但是“我如何理解大值的递归函数?” .

递归是解决某些类型问题的好工具。 如果由于某种原因,您不得不打印该数字序列,那么上面的代码将是解决问题的好方法。 递归也用于具有递归结构(如树或列表)或处理递归输入(如解析器)的上下文中。

您可能会看到递归函数的代码并想“这是做什么的?” 但更有可能出现相反的情况:您会发现需要通过编写程序来解决的问题。 有了经验,您将学会了解哪些问题需要递归解决方案,这是您作为程序员必须培养的技能。

递归的原理是重复执行一个[通常很简单]的函数。 所以要理解一个递归函数,你通常只需要理解一个步骤,以及如何重复它。

使用上面的代码,您不一定需要回答“这段代码给出了什么输出”,而是“它是如何工作的,以及代码遵循什么过程”。 你可以在纸上做这两件事。 通过逐步执行算法,您通常可以深入了解它的作用。 使这个例子复杂化的一个因素是它不是尾调用递归 这意味着您必须做更多的工作来理解程序。

要“理解”任何程序,您不一定需要能够模拟它并计算输出,这里也同样适用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM