本文介绍了递归控制流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>

void printd(int n)
{
    if(n/10)
        printd(n/10);
    putchar(n%10+'0');
}

在上面的code考虑n作为正整数
它的值是123。

In the above code consider n as a positive integer and its value be 123.

第一次,123传递给printd(第一printd)
第二次,12被传递给printd(第二printd)
第三次,1传递给printd(第三printd)和打印的putchar 1

First time,123 is passed to printd (first printd)Second time,12 is passed to printd (second printd)Third time,1 is passed to printd (third printd) and putchar prints 1

然后,控制流向第二printd之后,什么是n的值?
因为它是一个自动变量它在第三printd值为1的消失,一旦函数结束,并在第二printd得到12的值。

Then after the control flows to second printd,what is the value of n?Since it is an automatic variable it's value of 1 in third printd vanishes once the function ends and gets the value of 12 in second printd.

如果是这样,第二printd将再次引发第三printd等等....

If so,second printd will again lead to third printd and so....

但节目精美打印123。

But the program beautifully prints 123.

在哪里我的控制流和值函数调用过程中变量的理解错在哪里?

Where did my understanding on control flow and values for variables during function invocation went wrong?

仅供参考,该方案是从K&安培; R 4.10递归

FYI,the program is from K&R section 4.10 recursion

推荐答案

您错了位置:

如果是这样,第二printd将再次引发第三printd

第二个 printd 从停止开始,而不是从功能 printd 的开始。因此,的putchar 在第二个执行 printd 它打印2,同样的事情发生在第一个 printd ,打印3。

second printd starts from where it stopped, and not from the start of the function printd. So, the putchar is executed in second printd which prints 2 and the same thing happens in the first printd, printing 3.

这篇关于递归控制流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 19:37