我需要创建函数将十进制数转换为二进制,并以这种方式可视化该过程:
例如15:
15|1
7 |1
3 |1
1 |1
number 15 in binary is 1111 (from bottom to up).
我一直在尝试这样做,但是我什至不知道,我的功能是否正确。我知道python具有内置的“ bin”功能,但是无法将其用于可视化(或者我错了吗?)。
我的最后一个代码:
FinalList = []
dividedList = []
number = 29
while number != 1:
divided = number%2
number = int(number/2)
FinalList.append(divided)
dividedList.append(number)
print(divided)
if number == 0:
print(0)
FinalList.append(divided)
dividedList .append(0)
else:
print(1)
FinalList.append(1)
dividedList.append(1)
print(FinalList)
print(dividedList)
有人可以帮我吗?
我的输出为230:
[0, 1, 1, 0, 0, 1, 1, 1]
[115, 57, 28, 14, 7, 3, 1, 1]
并且应该是:
[0, 1, 1, 0, 0, 1, 1, 1]
[230,115, 57, 28, 14, 7, 3, 1]
希望这可以帮助!
小改动您的代码
FinalList = []
dividedList = []
number = 29
print(bin(number))
while number != 1:
_new_number, divided = divmod(number, 2)
print("{}|{}".format(number, divided))
number = _new_number
FinalList.append(divided)
dividedList.append(number)
if number == 0:
print('0|0')
FinalList.append(divided)
dividedList .append(0)
else:
print('1|1')
FinalList.append(1)
dividedList.append(1)
print(FinalList[::-1]) # should match with the `bin` result
print(dividedList)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句