2016-04-02 30 views
0

我创建了一个数字转换器,我需要将整数转换为二进制。当我试图转换整数12。它给我一个值0 0 0 0 0 1 0 0而不是0 0 0 0 1 1 0 0将整数转换为二进制返回错误的值

代码:

number = int(input("Enter a integer between 255 and 0: ")) 
    if (number > 255) or (number < 0): 
     print("Please input less than 255!!!") 
    else: 
     a = False 

     for myCounter in range (8): 

      if (number % 2 == 1):#if remainder is equal to 1 
       myResult = ' 1 ' + myResult#add '1' character to the string 

      else: 
       (number % 2 == 0)#if input has no remainder 
       myResult = ' 0 ' + myResult#add '0' character to the string 

      number = number/2 

     print("Binary equivalent is: %s" %myResult) 

Screenshot

我如何四舍五入的0.51使用ROUND_HALF_UP?输出如下。

Output

任何帮助将不胜感激谢谢!

+0

'math.ceil(0.5)' - >'1.0'是你想要的吗? (或者只加0.5和截断:'int(n + 0.5)') –

+2

尝试'number = number // 2' –

+0

请不要在'if'中使用圆括号 –

回答

0

该代码在Python 2.7中正常工作。对于Python 3.x尝试更换number = number/2number=number//2

number = 12 
a = False 
myResult = '' 
for myCounter in range (8): 

    if (number % 2 == 1):#if remainder is equal to 1 
     myResult = ' 1 ' + myResult#add '1' character to the string 

    else: 
     (number % 2 == 0)#if input has no remainder 
     myResult = ' 0 ' + myResult#add '0' character to the string 

    number = number // 2 

print("Binary equivalent is: %s" %myResult) 
+0

谢谢这帮了我!为什么我应该使用'Floor Division'而不是'Division Symbol'? – Francisunoxx

+0

@MiaLegaspi yep :) –

+1

对于那些更倾向于使用按位操作的人,'myResult = str(number&1)+ myResult;数字>> = 1'也会这样做。 – Reti43