我正在开发一个模拟自动售货机的程序。对于我的代码的这一部分创建了一个无限循环,我不太明白为什么。我通过 python tutor 运行它以查看我的问题出在哪里,似乎当我的变量 price_remaining = 5 时它有时不会通过 elif 语句。我不完全确定什么会以某种方式触发它。我将把我输入的内容复制并粘贴到 python tutor 中,希望有人可以基于此进行解释。 编辑:我刚刚通过 python tutor 检查了一些,它似乎只发生在我有 price_remaining 的值以 5 结尾。例如 2.05、0.05、1.15 等。
price_remaining = 2.55
price_remaining = price_remaining * 100
q_stock = 25
q_returned = -0
d_stock = 25
d_returned = 0
n_stock = 25
n_returned = 0
while price_remaining > 0:
if price_remaining >=25 and q_stock > 0:
price_remaining = price_remaining - 25
q_stock = q_stock - 1
q_returned = q_returned + 1
elif price_remaining >=10 and d_stock > 0:
price_remaining = price_remaining - 10
d_stock = d_stock - 1
d_returned = d_returned + 1
elif price_remaining >=5 and n_stock > 0:
price_remaining = price_remaining -5
n_stock = n_stock - 1
n_returned = n_returned + 1
print( q_returned)
print( d_returned)
print( n_returned
)
最佳答案
当我添加行时
print(repr(price_remaining), repr(n_stock))
在您的 while
的开头循环,代码产生
254.99999999999997 25
229.99999999999997 25
204.99999999999997 25
179.99999999999997 25
154.99999999999997 25
129.99999999999997 25
104.99999999999997 25
79.99999999999997 25
54.99999999999997 25
29.99999999999997 25
4.999999999999972 25
4.999999999999972 25
4.999999999999972 25
[.. forever ..]
由于 float 的工作方式(请参阅 here 以获取提醒),您不能总是完美地表示每个可能的数字,因此不能代表所有的 9。
无论如何,一次price_remaining < 5
,即使它只是少了一点点,你的代码也没有任何 if
触发的分支。
关于python - (Python 3.3)无法弄清楚为什么当值达到 5 时函数会创建无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14513997/