转换之后,我需要对它执行一些操作(例如,加法)。我还需要打印指定宽度的结果。在
为了完成上述任务,我编写了以下代码:
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:
在
你想知道有没有其他更好的方法?我知道可以使用bin()
函数,但是它返回一个字符串,所以我不能对它执行(integer)操作。在
另外,如果有任何评论可以改进代码,我将非常感激,因为我是Python的初学者。在
这似乎是在做我想做的事。下面的代码是根据我在问题中给出的原始代码构建的,建议来自Code Review。在
相关问题 更多 >
编程相关推荐