C和Python中递归函数的不同输出

2024-06-26 00:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用C和Python实现的drawPyramid_recursive函数。他们的逻辑是一样的。然而,它们的输出是不同的。为什么会这样?C和Python递归的函数调用堆栈中是否存在差异


C版本:

#include <stdio.h>

void drawPyramid_recursive(int height, int level)
{
    if (level == 0) // base case
    {
        return;
    }
    
    return drawPyramid_recursive(height, level - 1);

    for (int column = height - level; column >= 1; --column)
    {
        printf(" ");
    }

    for (int column = 1; column <= level; ++column)
    {
        printf("#");
    }

    printf("  ");

    for (int column = 1; column <= level; ++column)
    {
        printf("#");
    }

    printf("\n");
}

int main(void)
{
    int height;
    do
    {
        printf("Height: ");
        scanf("%i", &height);
    }
    while (height > 8 || height < 1);

    drawPyramid_recursive(height, height);
}

C版本的输出:

Height: 3
  #  #
 ##  ##
###  ###

Python版本:

def drawPyramid_recursive(height, level):
    if (level == 0):  # base case
        return

    drawPyramid_recursive(height, level - 1)

    for level in range(1, height + 1):
        for column in range(height - level, 0, -1):
            print(" ", end="")

        for column in range(1, level + 1):
            print("#", end="")

        print("  ", end="")

        for column in range(1, level + 1):
            print("#", end="")

        print()


def main():
    while True:
        height = input("Height: ")
        height = int(height)
        if (height >= 1 and height <= 8):
            break

    drawPyramid_recursive(height, height)


if __name__ == "__main__":
    main()

Python版本的输出:

Height: 3
  #  #
 ##  ##
###  ###
  #  #
 ##  ##
###  ###
  #  #
 ##  ##
###  ###

Tags: in版本forifmainrangecolumnlevel
2条回答

两件事:

第一:

The logic is the same among them.

不,逻辑是不同的。请再看一看Python代码中的for level in range(1, height + 1):行,它没有出现在C代码中

第二:
您可能应该去掉C代码中return drawPyramid_recursive(height, level - 1);行开头的关键字return。否则您将无法打印任何#。。。请参见此处:https://godbolt.org/z/TYYvWzqKb

在Python代码中,有以下代码:

for level in range(1, height + 1):
    for column in range(height - level, 0, -1):
        print(" ", end="")

但是在你的C代码中,没有任何等价物

考虑在C代码中添加:

for(int level = 1; level <= height; ++level)
{
    for(int column = height - level; column >= 0;  column)
    { 
        printf(" ");
    }
}

另外,在C版本中,您return drawPyramid_recursive(height, level - 1);但在Python版本中没有返回:drawPyramid_recursive(height, level - 1)您应该删除return,并将C代码更改为:drawPyramid_recursive(height, level - 1);

相关问题 更多 >