1

在这个 Python 代码中,我有以下问题。当显示结果时,我在结果中得到一堆零(见下文) - 否则,结果是正确的(字符串的结尾数字)。任何人都可以发现错误吗?

def menu():
    binNumber = ''
    decNumber = float(input("Enter a positive number: "))
    decNumber, binNumber = decimalToBinary(decNumber, binNumber)

    printResult(binNumber)

def decimalToBinary(dec, bin):
    while dec != 0:
        remain = dec % 2
        dec = dec / 2
        if remain > 0.5:
            bin += '1'
        else:
            bin += '0'
    return dec, bin

def printResult(binNumber):
    print("The binary notation is:", binNumber[::-1]) # the last part is to reverse the string

menu()

如果我输入“2”,这就是结果

二进制表示法是:00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010

4

2 回答 2

1

改变

decNumber = float(input("Enter a positive number: "))

decNumber = int(input("Enter a positive number: "))

并使用整数除法。代替

dec = dec / 2

利用

dec = dec // 2

通过这些更改,我得到以下输出

The binary notation is: 10
于 2013-10-05T11:36:03.060 回答
0

@Ragnar,在我应该提到你的代码是错误的之前。我尝试使用此代码转换 12 和 41,但失败了。要获得完整的帮助,我建议您查看此问题

于 2013-10-05T13:24:37.393 回答