不使用bin()函数将十进制转换为二进制且不打印结果

4

我尝试编写一个算法,可以将一个数字转换成二进制并打印出来,但不知何故程序在打印之前就停止了。

exponent = 4
binary = ""
def decToBin(userInput):
    global exponent, binary
    while (2**exponent) == 0:
        if (2**exponent) <= userInput:
            userInput = userInput - (2**exponent)
            binary = binary + "1"
        else:
            binary = binary + "0"
        exponent = exponent - 1
    return binary
print(decToBin(16))

如果你只想打印整数的二进制,为什么不使用print("{0:b}".format(16))? - Paolo Irrera
2个回答

1
你需要将 while (2**exponent) == 0 改为 while exponent >= 0,否则你永远无法进入或退出 while 循环,因为 2**exponent 始终大于 0,尽管每次迭代都会减少 exponent。此外,没有必要使用 global exponent, binary;只需将它们放在函数内部即可。
请注意,对于你选择的 exponent = 4userInput 应该限制在范围 [0, 2**(exponent + 1) - 1] = [0, 31] 内。
以下是一种替代算法(假设 userInput 是正整数):
def decToBin(userInput):
    if userInput == 0:
        return '0'
    binary = ''   
    while userInput > 0:
        binary = str(userInput % 2) + binary
        userInput //= 2
    return binary

-1

它为什么要做任何事情?

您使用userInput为16和exponent4启动它。2 ** 4 == 1616 != 0,因此您的while 2 ** exponent == 0从未触发,也从未进入其块...

您需要

while exponent > 0: 

为了得到你的结果。在每个循环中,你都会减少指数,所以一旦它越过0进入负数,你就完成了 - 不是一旦2 **指数做了什么。


我不知道downvoter的原因,但你建议的倒置测试将导致无限循环(或者说,它会在浮点下溢时停止)。 - user2357112

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接