2015-12-02 81 views
0

使用重複的部門如何十進制轉換爲二進制通過使用Python中反覆分裂?如何十進制轉換爲二進制在蟒蛇

我知道我必須使用while循環,並使用模數標誌和其他{%}和{//}要做到這一點......但我需要某種形式的例子,我的理解它是如何完成的,所以我完全可以理解。 指正,如果我錯了:

number = int(input("Enter a numberto convert into binary: ")) 

result = "" 
while number != 0: 
    remainder = number % 2 # gives the exact remainder 
    times = number // 2 
    result = str(remainder) + result 
    print("The binary representation is", result) 
    break 

謝謝

+0

您是否收到任何錯誤? – hdost

+0

正確的pep8格式 –

回答

0

製作一個「破發」,沒有任何條件,使循環沒用,所以代碼只執行一次,不管是什麼。

-

如果您不需要保留原來的號碼,你可以改變「數量」,當您去。

如果您確實需要保留原來的號碼,你可以像「時代」不同的變量。

你似乎這兩種情況混合在一起。

-

如果你想打印的所有步驟,打印將在循環內部,它打印多次。

如果你只想打印最終結果,則刊出外循環。

while number != 0: 
    remainder = number % 2 # gives the exact remainder 
    number = number // 2 
    result = str(remainder) + result 
print("The binary representation is", result) 

-

級聯線:

把打印循環內可能會幫助你看到它是如何工作的。

,我們可以打一個比方:

的結果值可能是「11010」(字符串,用引號)

在剩餘價值可能爲0(整數,不包括引號)

STR(剩餘部分)打開其餘爲0

= 「0」,而不是一個字符串,所以當我們在看賦值語句:

result = str(remainder) + result 

賦值運算符右側=首先evaulated。

的=右側是

str(remainder) + result 

,正如我們去了上述具有值:

"0" + "11010" 

這是字符串連接。它只是把一個字符串放在另一個字符串的末尾。結果是:

"0  11010" 

"011010" 

這是在賦值語句右側評估的值。

result = "011010" 

現在這就是結果的值。

+0

謝謝你喲,還有一個問題...我需要知道...什麼是「str(餘數)+結果」呢?特別是餘下的「str」函數,它做什麼......這使得這段代碼有效。預先感謝 – hameed

+0

你能解釋一下嗎...「str(餘數)+結果」是什麼?特別是「str」函數之前的其餘部分..呢? @beauxq – hameed

+0

@hameed添加到答案 – beauxq