簡體   English   中英

我正在學習recusive function,我只是不明白結果

[英]I'm learning recusive function and I just don't understand the result

#include <cs50.h>
#include <stdio.h>

void draw(int h);
int main(void)
{
    int height = get_int("Height: \n");
    draw(height);
}

void draw(int h)
{
    if (h ==0)
    {
        return;
    }
    draw(h - 1);
    for (int i = 0; i < h; i++)
    {
        printf("#");
    }
    printf("\n");

}

所以它打印出“# ## ### ####”(每一行都有空格)我不明白繪圖(高度),它一直減到0,但是for循環如何打印hash這樣的? 就像它在遞歸 function 將其減去 0 之后如何在遞增行中打印一樣? 請逐步解釋它是如何工作的,在此先感謝您。

執行打印行的第一次調用draw()將是draw(1) ,因為您首先調用draw(h - 1) ,因此調用將堆疊在堆棧中,然后在for之前執行。

試圖簡化序列:

=> draw(3);
==> Calls: draw(2);
===> Calls: draw(1);
====> Calls: draw(0) <=== return to [draw(1)];
===> draw(1): run the for ("#") <== return to [draw(2)]
==> draw(2): run the for ("##") <== return to [draw(3)]
=> draw(3): run the for ("###") <== return to first caller

結果:
# ## ###


為了更好地理解,您可以切換draw(h - 1) for順序:

for (int i = 0; i < h; i++)
{
    printf("#");
}
draw(h - 1);

你會得到:
### ## #

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM