Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将整数转换为二进制将返回错误的值_Python_Python 3.x_Binary_Integer - Fatal编程技术网

Python 将整数转换为二进制将返回错误的值

Python 将整数转换为二进制将返回错误的值,python,python-3.x,binary,integer,Python,Python 3.x,Binary,Integer,我创建了一个数字转换器,需要将整数转换为二进制。当我试图转换整数12时。它给了我一个值0 0 0 0 0 1 0,而不是0 0 0 0 1 0 代码: number=int(输入(“输入一个介于255和0之间的整数:”) 如果(编号>255)或(编号1.0这就是你想要的吗?(或者只需添加0.5并截断:int(n+0.5))尝试number=number//2请不要在中使用括号,如果@RicardoCruz不是。谢谢这帮助了我!为什么我应该使用Floor Division而不是Division S

我创建了一个数字转换器,需要将整数转换为二进制。当我试图转换整数
12
时。它给了我一个值
0 0 0 0 0 1 0
,而不是
0 0 0 0 1 0

代码:

number=int(输入(“输入一个介于255和0之间的整数:”)
如果(编号>255)或(编号<0):
打印(“请输入小于255!!!”)
其他:
a=错误
对于范围(8)内的myCounter:
if(数字%2==1):#如果余数等于1
myResult='1'+myResult#在字符串中添加'1'字符
其他:
(数字%2==0)#如果输入没有余数
myResult='0'+myResult#在字符串中添加'0'字符
数字=数字/2
打印(“二进制等价物为:%s”%myResult)

如何使用向上舍入法将
0.5
四舍五入到
1
?输出如下


任何帮助都将不胜感激,谢谢

该代码在Python 2.7中运行良好。请尝试将
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)

math.ceil(0.5)
->
1.0
这就是你想要的吗?(或者只需添加0.5并截断:
int(n+0.5)
)尝试
number=number//2
请不要在
中使用括号,如果
@RicardoCruz不是。谢谢这帮助了我!为什么我应该使用
Floor Division
而不是
Division Symbol
?@MiaLegaspi-yep:)对于那些更倾向于使用位运算的人,
myResult=str(number&1)+myResult;数字>>=1
也会这样做。
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)