[英](Python 3.3) Can not figure out why function creates infinite loop when value gets to 5
I'm working on a program that simulates a vending machine. 我正在开发一个模拟自动售货机的程序。 For some this section of my code creates an infinite loop, I cant quite figure out why.
对于我的代码的这一部分,某些部分会创建一个无限循环,我无法弄清楚为什么。 I ran it through python tutor to see where my problem was, it seems that when my variable price_remaining = 5 it will sometimes not go through the elif statement.
我通过python导师运行它来查看问题所在,似乎当我的变量price_remaining = 5时,有时它不会通过elif语句。 I'm not entirely sure what would trigger it one way or another.
我不完全确定是什么原因会触发它。 I'm going to copy and paste what I entered in to python tutor in hopes that someone can explain based on that.
我将把我输入的内容复制并粘贴到python导师中,希望有人可以以此为基础进行解释。 EDIT: I just checked through python tutor some more, it appears to only occur when I have a value for price_remaining ending with a 5. For example 2.05,0.05, 1.15, etc.
编辑:我只是通过python导师检查了更多,它似乎仅当我有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
) )
When I add the line 当我添加线
print(repr(price_remaining), repr(n_stock))
at the start of your while
loop, the code produces 在
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 ..]
Because of how floating point numbers work (see here for a reminder), you can't always perfectly represent each possible number, hence all the 9s. 由于浮点数是如何工作的(请参阅此处以获取提示),您不能总是完美地表示每个可能的数字,因此不能全部表示9。
In any case, once price_remaining < 5
, even if it's only less by a tiny amount, your code doesn't have any if
branch which triggers. 在任何情况下,一旦
price_remaining < 5
,即使它只是很小的一部分,您的代码也不会触发任何if
分支。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.