2016-04-02 33 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