简体   繁体   English

0砖金字塔建筑python的错误输出

[英]Wrong output with 0 bricks pyramid building python

I'm making a small script that builds a pyramid out of the users input number, it then outputs the maximum height it can go to.我正在制作一个小脚本,根据用户输入的数字构建一个金字塔,然后输出它可以达到的最大高度。

 for n in range(bricks):
     if (n*n)/2 <= bricks:
         height = n+1
     print("The height of the pyramid is:", height)

When I put "0" in it still puts height of "1", I get that's because of the +1 but without that there it will give a syntax error, and will also display the wrong height when putting just "1" brick in, any ideas on how to fix this.当我在里面放“0”时,它仍然把高度设为“1”,我知道这是因为+1,但如果没有它,它会出现语法错误,并且在只放入“1”砖时也会显示错误的高度, 有想法该怎么解决这个吗。

Thanks谢谢

You may desindent the print, it may run at the end of the loop您可以设计打印,它可以在循环结束时运行

bricks= 0
height = 0
for n in range(bricks):
    if (n*n)/2 <= bricks:
        height = n+1
print("The height of the pyramid is:", height)

If you extract a method, you'll have如果您提取一个方法,您将拥有

def get_height(bricks):
    height = 0
    for n in range(bricks):
        if (n * n) / 2 <= bricks:
            height = n + 1
    return height

for b in range(10):
    print("The height of the pyramid is:", get_height(b), 'for nb_bricks=', b)
The height of the pyramid is: 0 for nb_bricks= 0
The height of the pyramid is: 1 for nb_bricks= 1
The height of the pyramid is: 2 for nb_bricks= 2
The height of the pyramid is: 3 for nb_bricks= 3
The height of the pyramid is: 3 for nb_bricks= 4
The height of the pyramid is: 4 for nb_bricks= 5
The height of the pyramid is: 4 for nb_bricks= 6
The height of the pyramid is: 4 for nb_bricks= 7
The height of the pyramid is: 5 for nb_bricks= 8
The height of the pyramid is: 5 for nb_bricks= 9

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

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