简体   繁体   English

金字塔问题返回错误的 output

[英]Returns wrong output for the pyramid problem

For this coding exercise I have to input a number of imaginary blocks and it will tell me how many complete rows high the pyramid is.对于这个编码练习,我必须输入一些虚构的块,它会告诉我金字塔有多少完整的行高。

For example, if I input 6 blocks, I want it to tell me that the height of the pyramid is 3 (3 blocks on the bottom, 2 above that, and 1 above that).例如,如果我输入 6 个块,我希望它告诉我金字塔的高度是 3(底部 3 个块,上方 2 个块,上方 1 个块)。

blocks = int(input("Enter the number of blocks: "))
height=0
count=1
while(blocks>1):
    for i in range(0,count):
        blocks -= 1
    count +=1 
    height += 1

print("The height of the pyramid:", height)

It works for 6, but for 1000, it should return 44 but instead I get 45?它适用于 6,但对于 1000,它应该返回 44 但我得到 45? What's wrong with my code?我的代码有什么问题?

问题

You need to add to the count before the for loop and add an ='s.您需要在 for 循环之前添加计数并添加 =。

blocks = int(input("Enter the number of blocks: "))
height=0
count=1
while(blocks>=1):
    count +=1
    height += 1
    for i in range(0,count):
        blocks -= 1


print("The height of the pyramid:", height)

Here is an implementation with just a while loop这是一个只有一个while循环的实现

number=1000
count=0
while number >= count:
    count +=1
    number -= count

print(count)

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

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