【问题标题】:The output halts when entered any positive integer. The problem must be in the while loop输入任何正整数时输出停止。问题一定出在while循环中
【发布时间】:2020-05-14 02:41:27
【问题描述】:
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 循环,但无法获得球的整个轨迹。

【问题讨论】:

  • 将正值重复乘以 0.6 不会使其为零或负(数学上)。由于舍入错误,如果您等待足够长的时间,它可能会变为零。
  • 我投票结束这个问题,因为这显然是一个数学问题,而不是编程问题。

标签: python loops while-loop execution


【解决方案1】:

正如用户@MichaelButscher 上面提到的,将一个正值重复乘以系数(在这种情况下为0.6)将接近于零,但永远不会到达那里。如果您在 while 循环中打印出 height,您可以看到这一点。您必须将height 的限制设置为不同的数字(例如:我将while (height&gt;0) 更改为while (height&gt;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。

【讨论】:

    【解决方案2】:
    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)
    

    【讨论】:

    • while (count>0) 总是假的
    猜你喜欢
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 2021-09-28
    • 1970-01-01
    • 2020-09-02
    • 2013-09-28
    相关资源
    最近更新 更多