Python 3.x 修复Python循环未执行最后一行时的问题

Python 3.x 修复Python循环未执行最后一行时的问题,python-3.x,Python 3.x,我编写的代码不会执行程序中的最后一次计算 height = float(input("Enter the height from which the ball is dropped: ")) index = float(input("Enter the bounciness index of the ball: ")) bounces = float(input("Enter the number of times the ball bounces: ")) distance = 0 w

我编写的代码不会执行程序中的最后一次计算

height = float(input("Enter the height from which the ball is dropped: "))

index = float(input("Enter the bounciness index of the ball: "))

bounces = float(input("Enter the number of times the ball bounces: "))

distance = 0

while bounces > 0:

    distance = height*index

    x = distance*index

    y = x*index

    td = distance + x + y

    totald = td*bounces

    bounces -= 1

print()

print("Total distance traveled is %.3f" % totald)
我希望计算的结果是:反弹(距离+x+y)=总数

例3(12.5+6.25+3.125)=65.625

但它只打印出以下计算:距离+x+y=总计


例12.5+6.25+3.125=21.875‬

您面临这个问题,因为在任何迭代中,
反弹
都是递减的,
totald
设置为
bounce*td
。因此,“totald”的最终值是在最后一次迭代中确定的,其中
bounce
1
。为了防止此问题,您可以在每次迭代中将
td*bounce
的值添加到
totald

试试这个:

distance = 0
totald = 0

while bounces > 0:

    distance = height*index

    x = distance*index

    y = x*index

    td = distance + x + y

    totald += td

    bounces -= 1

print()

print("Total distance traveled is %.3f" % totald)
或者简单地说:

distance = 0
totald = 0

if bounces > 0:

    distance = height*index

    x = distance*index

    y = x*index

    td = distance + x + y

    totald = td*bounces

print()

print("Total distance traveled is %.3f" % totald)

您希望总数乘以3的位置?对于本测试,是的。但总的来说不是。我试图创建一个程序来计算输入的任何数字。但首先遇到了这个问题,无法通过,无法前进。你应该解释你的答案。转储代码不是非常有用。非常感谢。你能不能提供我需要修改的代码行,使代码的执行能力超过3的倍数?