【问题标题】:Converting from decimal to binary without using bin() not printing从十进制转换为二进制而不使用 bin() 不打印
【发布时间】:2019-03-17 07:11:53
【问题描述】:

我试图创建一个算法来打印一个数字的二进制值,但由于某种原因它退出而不是打印。

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)) ?

标签: python function binary decimal


【解决方案1】:

您需要将while (2**exponent) == 0 更改为while exponent &gt;= 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

【讨论】:

    【解决方案2】:

    为什么它应该做任何事情?

    您从 16 的 userInput4exponent 开始。 2**4 == 1616 是 != 0 所以你的 while 2**exponent == 0 永远不会触发并且永远不会进入它的块......

    你需要

    while exponent > 0: 
    

    得到你的结果。您正在减少每个循环上的指数,因此一旦它越过 0 变为负数,您就完成了 - 不是一次 2**exponent 确实如此。

    【讨论】:

    • 我不知道downvoter的原因,但是你建议的倒置测试会导致无限循环(或者更确切地说,它会在遇到浮点下溢时停止)。
    猜你喜欢
    • 2013-10-26
    • 2015-04-24
    • 2013-03-31
    • 2019-06-10
    • 2015-09-16
    • 1970-01-01
    • 2012-11-13
    相关资源
    最近更新 更多