Python:十进制到二进制

标签 python

我正在尝试让该函数正常工作,它应该将十进制转换为二进制,但它却给了我不同的数字。就像如果我输入 12,它会给我 2。我不确定我的问题在代码中的什么位置。任何帮助都会很棒,谢谢!

def decimalToBinary(value):
    if value < 0: #Base case if number is a negative
        return 'Not positive'
    elif value == 0: #Base case if number is zero
        return 0
    else:
        return decimalToBinary(value//2) + (value%2)

最佳答案

这也可以工作

def DecimalToBinary(number):
        #This function uses recursion to convert & print decimal to binary number
       if number > 1:
           convertToBinary(number//2)
       print(number % 2,end = '')

    # decimal number
    decimal = 34

    convertToBinary(decimal)
    #..........................................
    #it will show output as 110100

关于Python:十进制到二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35656482/

相关文章:

python - 将多个键与 LRUCache 一起使用

python - 在 Sklearn 中留下一个

python - 比较列表以查找 python 中的公共(public)元素

python - django 中的 csrf 错误

python - 在 Windows 10 上安装 opencv for Python 3.6.3 时出现 DLL Load failed 错误

python - 用于插入文本小视频的服务器要求 ffmpeg

python - 有没有一种快速的方法来添加两个三维数组?

python - PyInstaller 新手 : hello world

python - 将元素保留在另一个列表中包含的元组列表中

python - 为什么我安装的应用程序处理 pkg_resources.iter_entry_points 的方式与源代码不同?