2016-12-27 102 views
-1
  1. 鑑於小數我需要將其轉換成二進制
  2. 給定一個二進制數我需要將其轉換成十進制

轉換後我需要對其執行一些操作(例如,添加)。另外我需要用指定的寬度打印結果。十進制轉換爲二進制的轉換,反之亦然在Python

爲實現上述我寫了下面的代碼:

Binary-Decimal:

n1 = int(input("Enter a binary number: ")) 
    n2 = int(input("Enter a binary number: ")) 

    # type cast to 'int' is done to provide width 
    decimalN1 = int("{0:d}".format(n1), 2) 
    decimalN2 = int("{0:d}".format(n2), 2) 
    decimalSum = int("{0:d}".format(n1 + n2), 2) 

    width = len(str(decimalSum)) 
    print("max width = {}".format(width)) 

    print ("{0:0{3}} + {1:0{3}} = {2:0{3}}".format(decimalN1, decimalN2, decimalSum, width)) 
    print ("{0} + {1} = {2}".format(type(decimalN1), type(decimalN2), type(decimalSum))) 

Decimal-Binary:

n1 = int(input("Enter a decimal number: ")) 
    n2 = int(input("Enter a decimal number: ")) 

    # type cast to 'int' is done to provide width 
    binaryN1 = int("{0:b}".format(n1)) 
    binaryN2 = int("{0:b}".format(n2)) 
    binarySum = int("{0:b}".format(n1 + n2)) 

    width = (n1 + n2).bit_length() 
    print("max width = {}".format(width)) 

    print ("{0:0{3}} + {1:0{3}} = {2:0{3}}".format(binaryN1, binaryN2, binarySum, width)) 
    print ("{0} + {1} = {2}".format(type(binaryN1), type(binaryN2), type(binarySum))) 

什麼是想知道有沒有其他的(更好)的方式這樣做?我知道bin()函數可以使用,但它然後返回一個字符串,所以我不能執行(整數)操作。

此外,任何評論意見,以改善代碼將非常讚賞,因爲我是一個Python初學者。

+0

如果這是您認爲可以改進的**工作代碼**,請參閱[codereview.se]。一個明顯的問題是,你要求用戶輸入二進制,然後立即將其轉換爲一個整數*作爲十進制輸入*,這似乎適得其反。 – jonrsharpe

+0

謝謝,感謝 – Orion

回答

0

這似乎在做我想做的事情。建議如下代碼基於我在問題中給出的原始代碼Code Review的建議。

#!/usr/bin/python3 

# this function accepts a decimal integer and returns a binary string 
def decimalToBinary (decimalInt) : 
    return "{0:b}".format (decimalInt) 
# this function accepts a binary string and returns a decimal integer 
def binaryToDecimal (binaryString) : 
    return int (binaryString, 2) 

x = int (input ("Enter a decimal number: ")) 
y = int (input ("Enter a decimal number: ")) 
sumInDecimal = x + y 
print ("{0} when converted to binary is {1}".format (x, decimalToBinary(x))) 
print ("{0} when converted to binary is {1}".format (y, decimalToBinary(y))) 
print ("Addition in base 10: \t {0} + {1} = {2}".format (x, y, x + y)) 
print ("Addition in base 2: \t {0} + {1} = {2}".format (decimalToBinary(x), decimalToBinary(y), decimalToBinary(sumInDecimal))) 
print() 
x = input ("Enter a binary number: ") 
y = input ("Enter a binary number: ") 
# convert binary to decimal before any operation, the result of the operation will be in decimal 
sumInDecimal = binaryToDecimal(x) + binaryToDecimal(y) 
print ("{0} when converted to decimal is {1}".format (x, binaryToDecimal(x))) 
print ("{0} when converted to decimal is {1}".format (y, binaryToDecimal(y))) 
print ("Addition in base 2: \t {0} + {1} = {2}".format (x, y, decimalToBinary(sumInDecimal))) 
print ("Addition in base 10: \t {0} + {1} = {2}".format (binaryToDecimal(x), binaryToDecimal(y), sumInDecimal))