gpt4 book ai didi

python - 整数到二进制转换

转载 作者:行者123 更新时间:2023-11-30 23:45:12 24 4
gpt4 key购买 nike

我计算从整数到二进制数的转换是错误的。我输入了整数6,得到了二进制数0。这肯定是错误的。你们能帮忙吗?顺便说一句,我正在使用 python 3。

def ConvertNtoBinary(n):

binaryStr = ''
if n < 0:
print('Value is a negative integer')

if n == 0:
print('Binary value of 0 is 0')
else:
if n > 0:
binaryStr = str(n % 2) + binaryStr
n = n > 1
return binaryStr

def main():
n = int(input('Enter a positive integer please: '))
binaryNumber = ConvertNtoBinary(n)
print('n converted to a binary number is: ',binaryNumber)

main()

最佳答案

这里的问题是:

n = n > 1

这会进行 bool 比较“n 是否大于 1?”。您可能想要的是 n >> 1,即位移 n。

编辑:此外,您只执行此过程一次 - 我想您会希望在某些条件下执行此操作,例如

while n > 0:

EDIT2:John Machin 的评论是正确的,我修正了上面的内容以反射(reflect)这一点。

关于python - 整数到二进制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9691121/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com