【问题标题】:Performing arithmetic on floating point values of different sizes对不同大小的浮点值进行算术运算
【发布时间】:2015-09-08 16:22:31
【问题描述】:

如果一个浮点变量有 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 = 1000self.result = str("Please ensure...")
如果mmax = 9999, current = 5000, and mmin = 1000self.result = str("Capacity: 44.45%)

这是怎么回事/我该如何克服这个问题?

【问题讨论】:

  • floats 很多...你能澄清一下你的期望吗?另请注意,例如if not flag: 优于 if flag is False:,因为它更好地处理 不是 False 的 false-y 值。
  • 您应该检查mmaxcurrentmmin 的值是否确实符合您的预期。如果我只是强制它们为 10000、5000 和 1000,它会给出正确的结果。
  • @spectras 这是我从一个返回字符串的 tkinter 条目中获得 mmaxcurrentmmin 的问题,我在转换为浮点数之前直接对它们进行算术运算/整数。 @jonrsharpe 注意到了。

标签: python tkinter floating-point size tkinter-entry


【解决方案1】:

我猜mmincurrentmmax 是字符串。在这种情况下,这个表达式:

if mmin <= current <= mmax and 0 <= capacity <= 100:

... 正在对值进行字典比较。这与数值比较不同:例如,"5000" &lt; "10000" 的计算结果为 False,因为“5”大于“1”。

在对它们进行比较之前将您的值转换为数字。

if mmax.isdigit() and mmin.isdigit() and current.isdigit():
    mmax = float(mmax)
    current = float(current)
    mmin = float(mmin)

    capacity = float(100 * ... #etc

或者

if float(mmin) <= float(current) <= float(mmax) and 0 <= capacity <= 100:

【讨论】:

  • 在您收到询问者的反馈之前,我们无法确定,但考虑到这些症状,这似乎是一个很好的修复方法。 +1-ing
  • tkinter 标签是一个额外的线索,因为get() 是最常见的 Tkinter 输入框的方法,它返回一个字符串。
  • 另外,如果是数字,调用 isdigit 会出现语法错误。
  • 是的,我刚刚注意到这一点,这就是为什么我不得不编辑我的第一个建议,即在 get 调用周围包装 float
  • @Kevin 是的,我使用.get() 来本地化此功能中的 tkinter 条目,但我不知道 tkinter 条目总是返回字符串。 @saulspatz 你是对的。我试过mmax = float(self.mmax.get())isdigit 方法只适用于字符串。
猜你喜欢
  • 1970-01-01
  • 2019-03-25
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 2014-10-07
相关资源
最近更新 更多