【问题标题】:Using a loop to convert decimal to binary使用循环将十进制转换为二进制
【发布时间】:2021-12-10 14:41:51
【问题描述】:

我想编写一个程序,将十进制数字 0 到 9 转换为二进制。我可以编写如何使用重复除法将十进制数转换为二进制数的代码。但是,我无法创建一个循环以二进制格式打印出十进制数字 0 到 9。

这是我的代码

number = 0

remainder = 0
x = ""
while number (0,9):
    remainder = (number%2)
    x = str(remainder) + x
    number = number//2
   
    (x[::-1])
    print(number, "is the binary of",x)

【问题讨论】:

    标签: python loops if-statement while-loop binary


    【解决方案1】:

    这是您的代码的修复:

    number = 123
    remainder = 0
    x = ""
    n = number # don't work on the original number
               # you need it for the final print
    while n > 0:  # wrong syntax for the condition
        remainder = (n%2)
        x = str(remainder) + x
        n = n//2
        #(x[::-1])  # this is useless
    print(x, "is the binary of", number) # wrong order to print
    

    注意。您还应该利用divmod,而不是两个单独的%// 操作

    【讨论】:

      【解决方案2】:

      你可以这样做:

      number = 5
      n = number
      x = ""
      while n:
          x = str(n % 2) + x
          n //= 2
          
      print("Decimal:", number)
      print("Binary:", x)
      

      输出:

      Decimal: 5
      Binary: 101
      

      【讨论】:

        猜你喜欢
        • 2015-03-19
        • 2016-03-18
        • 1970-01-01
        • 1970-01-01
        • 2012-06-26
        • 1970-01-01
        • 2012-06-17
        • 1970-01-01
        • 2014-02-10
        相关资源
        最近更新 更多