简体   繁体   中英

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).

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? What's wrong with my code?

问题

You need to add to the count before the for loop and add an ='s.

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

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

print(count)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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