2016-12-27 152 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))