如果一个浮点变量有5位数,其他浮点数有4位,并且对它们执行算术运算,我的代码就不会像我预期的那样运行。例如:
def capacity(self):
mmax = self.mmax.get()
current = self.current.get()
mmin = self.mmin.get()
flag = False
if flag is False:
if mmax.isdigit() and mmin.isdigit() and current.isdigit():
capacity = float(100 * ((float(current) - float(mmin)) / (float(mmax) - float(mmin))))
if mmin <= current <= mmax and 0 <= capacity <= 100:
flag = True
else:
self.result = str("Please ensure the values entered correspond to the correct value.")
else:
self.result = str("Please enter only positive integers.")
if flag is True:
self.result = "Capacity: %2.2f" % capacity + '%'
如果mmax = 10000, current = 5000, and mmin = 1000
,self.result = str("Please ensure...")
如果mmax = 9999, current = 5000, and mmin = 1000
,self.result = str("Capacity: 44.45%)
。
这里发生了什么/我如何克服这个问题?
答案 0 :(得分:2)
我猜测<h1 style="text-align: center"; font-family="MinecrafterReg.ttf">Welcome to Ben's Minecraft</h1>
和mmin
以及current
是字符串。在这种情况下,这个表达式:
mmax
......正在对这些值进行词典比较。这与数字比较不同:例如,if mmin <= current <= mmax and 0 <= capacity <= 100:
的计算结果为False,因为“5”大于“1”。
在对值进行比较之前将值转换为数字。
"5000" < "10000"
或者
if mmax.isdigit() and mmin.isdigit() and current.isdigit():
mmax = float(mmax)
current = float(current)
mmin = float(mmin)
capacity = float(100 * ... #etc