在python中如何将十进制小数转换成二进制

在python中如何将十进制小数转换成二进制

在最近的学习中发现博客园里面找不到如何在python中如何将十进制小数转换成二进制,所以我用土方法写了一个超级简单的转换方法(不过转换出来的数只是形式上是二进制但是得出的数实际上是十进制的数)


import math
k = eval (input('Enter the count you want to translate: '))
count=abs(k)
A=math.floor(count)
a=math.floor(count)
b=0
while A>0:
     y=A%2
     A=A // 2
     b=b*10+y
str(b)[::-1]
B=count-a
t=8
N=0
while t>0:
    B=B*2
    N=N*10+math.floor(B)
    B=B-math.floor(B)
    t=t-1
N=N/100000000
L=b+N
if k>=0:
  print(L)
else:
  L=-L
  print(L)

  • 比如我们输入0.25

Enter the count you want to translate: 0.25
0.01

posted @ 2020-10-16 08:49  20201327刘谨铭  阅读(3336)  评论(0编辑  收藏  举报