【问题标题】:Unpack error in a function that converts float to binary将浮点数转换为二进制的函数中的解包错误
【发布时间】:2019-09-21 15:00:33
【问题描述】:

我正在尝试制作一个 Python 函数,它接受一个浮点数,并将其转换为带有二进制的字符串(也考虑小数部分,用点分隔),但对于某些值 - 例如 0.5、0.25 , 0.10, 0.05 , 0.05, ...- 它给出以下错误:

line 7, in floatToBinary integerPart, fractionalPart = str((convertDecimal(fractional))*2).split(".")
ValueError: Not enough values ​​to unpack (expected 2, got 1)

功能:

def floatToBinary(floatNumber, decimalPlaces):
    integerPart, fractionalPart = str(floatNumber).split(".")
    integerPart = int(integerPart)
    fractionalPart = int(fractionalPart)
    result = bin(integerPart).lstrip("0b") + "."
    for i in range(decimalPlaces):
        integerPart, fractionalPart = str((convertDecimal(fractionalPart))*2).split(".")
        fractionalPart = int(fractionalPart)
        result += integerPart
    return result

def convertDecimal(n):
    while n > 1:
        n /= 10
    return n

希望你能帮助我。

【问题讨论】:

    标签: python python-3.x floating-point binary unpack


    【解决方案1】:

    函数 convertDecimal 在 n = 0 时返回 0。所以没有 '.'分开。 您可以通过将返回值转换为浮点数来解决此问题

    def convertDecimal(n):
        while n > 1:
            n /= 10
        return float(n)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-24
      • 2017-06-24
      • 1970-01-01
      • 2011-04-26
      • 2021-07-30
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      相关资源
      最近更新 更多