我创建了一个数字转换器,我需要将Integer转换为Binary。当我尝试转换整数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)
如何使用ROUND_HALF_UP将0.5
四舍五入为1
?输出如下。
任何帮助都将不胜感激!
答案 0 :(得分:0)
代码在Python 2.7中运行良好。对于Python 3.x,请尝试将number = number/2
替换为number=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)