当输入任何正整数时,输出停止。问题必须在while循环中

问题描述 投票:0回答:1
height=int(input("Enter the height from which the ball is dropped: "))
count=0
travel_dist=0
index=0.6

    if height<=0:
        print("The ball cannot bounce...")
    else:
        while (height>0):
            travel_dist=height+(height*index)
            count+=1
            height=height*index
            if height<=0:
                break;
       print("The ball has bounced ", count, "and travelled the total distance of ", travel_dist)

我试着去掉while循环,但我无法得到球的整个轨迹。

python loops while-loop execution
1个回答
1
投票

正如用户@MichaelButscher在上面提到的,将一个正值与系数反复相乘(在这种情况下是0.6)会接近于零,但永远也不会达到。你可以看到,如果你打印出 height 在while循环中。你必须设置 height 改为不同的数字(例如:我把 while (height>0)while (height>2))这样。

height=int(input("Enter the height from which the ball is dropped: "))
count=0
travel_dist=0
index=0.6

if height<=0:
    print("The ball cannot bounce...")
else:
    while (height>2):
        travel_dist=height+(height*index)
        count+=1
        height=height*index
        print(height)
        if height<=0:
            break
    print("The ball has bounced ", count, "and travelled the total distance of ", travel_dist)

这代表的是一个球从最初的高度掉下来后,在上升到小于2的高度之前,会弹跳多少次。 你可以设置以下条件: height 到任何大于0的数字,如0.00001。


0
投票
while height >0  is always true therefore while loop runs infinite. 

通过检查计数值来纠正while循环条件。

while (count>0):

修改后的代码。

height=int(input("Enter the height from which the ball is dropped: "))
count=0
travel_dist=0
index=0.6

if height<=0:
     print("The ball cannot bounce...")
else:
     while (count>0):
        travel_dist=height+(height*index)
        count+=1
        height=height*index
        if height<=0:
           break;

     print("The ball has bounced ", count, "and travelled the total distance of ", travel_dist)
© www.soinside.com 2019 - 2024. All rights reserved.