我正在练习一些新获得的技能,并想利用社区对下面的代码提供一些反馈。
目标:创建一个简单的程序,通过解构变更的组成部分(美元,季度等)来帮助假想的收银员返回正确的变化。 我能想到这样做的最好方法是使用带有嵌套while循环的if语句。
2个问题:
1)。虽然条件runningTotal!=更改不再满足,但while循环不会在脚本结束时终止。为什么呢?是不是应该运行,直到满足该条件,并终止?我一定错过了一些东西......是否有一些明显的东西我想念你们/ gals看到了什么?
2)。我还是个初学者(你可能会说)。您在下面的脚本中对我有什么反馈。事情我做得很好,很差或只是一般的想法。我真的想要变得更好,所以你的评论非常感谢。谢谢!
剧本:
def changeCalc(cost,pmt):
change = float(pmt - cost)
print("Total Change: " + str(change))
runningTotal = 0 #used to count up the change paid in the while loop below
#make sure they paid enough
if (pmt - cost) < 0:
print("The customer needs to pay " + str(abs(change)) + " more.")
else:
#check to see if any change is due
while runningTotal != change:
#how many DOLLAR bills to return
dollarBills = int(change - runningTotal)
print("Number of Dollar Bills: " + str(dollarBills))
#add to runningTotal
runningTotal = float(runningTotal + dollarBills)
print runningTotal
#how many QUARTERS to return
numOFqtrs = int((change - runningTotal)/(.25))
print("Number of Quarters: " + str(numOFqtrs))
#add to running total
runningTotal = float(runningTotal + (numOFqtrs * (.25)))
print runningTotal
#how many DIMES
numOFdimes = int((change - runningTotal)/(.10))
print("Number of Dimes: " + str(numOFdimes))
runningTotal = float(runningTotal + (numOFdimes * (.10)))
#how many NICKELS
print runningTotal
numOFnickels = int((change - runningTotal)/(.05))
print("Number of nickels: " + str(numOFnickels))
runningTotal = float(runningTotal + (numOFnickels * (.05)))
print runningTotal
#how many PENNIES
numOFpennies = int((change - runningTotal)/(.01))
print("Number of Pennies: " + str(numOFpennies))
runningTotal = float(runningTotal + (numOFpennies * (.01)))
print runningTotal
print change
#####WHY DOES THE LOOP NOT END HERE??????????##########
break
运行changeCalc(87.63,103.86)导致无限循环,输出如下。
Total Change: 16.23
Number of Dollar Bills: 16
16.0
Number of Quarters: 0
16.0
Number of Dimes: 2
16.2
Number of nickels: 0
16.2
Number of Pennies: 3
16.23
16.23
答案 0 :(得分:1)
正如其他人所说,while
循环的问题是浮点精度:runningTotal
非常接近,但与{{1}不完全相同}}。你可以通过使用一些小的 epsilon 进行比较,或者使用整数或类似的来解决这个问题。
但是,您似乎根本不需要change
循环,是吗?此外,请注意,不同类型的硬币的代码是完全相同的,因此您可以使用循环来迭代所有不同类型的硬币:
while
答案 1 :(得分:0)
尝试打印change-runningTotal,您将看到它的大小为10e-15。这可能是由于浮子的使用。
您可以将循环的条件更改为:
“while runningTotal - 更改&lt; -0.001或runningTotal - 更改&gt; 0.001:”
使该计划有效。