我有一个用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
# #
## ##
### ###
# #
## ##
### ###
# #
## ##
### ###
两件事:
第一:
不,逻辑是不同的。请再看一看Python代码中的
for level in range(1, height + 1):
行,它没有出现在C代码中第二:
您可能应该去掉C代码中
return drawPyramid_recursive(height, level - 1);
行开头的关键字return
。否则您将无法打印任何#
。。。请参见此处:https://godbolt.org/z/TYYvWzqKb在Python代码中,有以下代码:
但是在你的C代码中,没有任何等价物
考虑在C代码中添加:
另外,在C版本中,您
return drawPyramid_recursive(height, level - 1);
但在Python版本中没有返回:drawPyramid_recursive(height, level - 1)
您应该删除return
,并将C代码更改为:drawPyramid_recursive(height, level - 1);
相关问题 更多 >
编程相关推荐