Python将十进制小数转化为二进制的代码
时间: 2023-06-03 10:04:10 浏览: 131
将十进制小数转换成二进制小数其过程如下-计算机系统概论第一章
以下是将十进制小数转化为二进制的Python代码:
def decimal_to_binary(decimal_num):
whole_num, decimal_part = str(decimal_num).split('.')
whole_num = int(whole_num)
decimal_part = float('.' + decimal_part)
binary_whole_num = bin(whole_num)[2:]
binary_decimal_part = ''
while decimal_part > 0:
decimal_part *= 2
if decimal_part >= 1:
binary_decimal_part += '1'
decimal_part -= 1
else:
binary_decimal_part += '0'
return binary_whole_num + '.' + binary_decimal_part
阅读全文