我试图为十进制数字编写二进制表达式。这是我的代码:
value=0.375
result=""
while(value<1):
value*=2
if(value>=1):
value-=1
result+=str(1)
break
result+=str(0)
print(result)
输出:01 ,但必须为 011
我想通过将值减1来再次运行while循环,但这似乎不起作用。
答案 0 :(得分:0)
这是正确的逻辑:
ENOUGH_PRECISION = 20 # Enough number of 1's and 0's in the output
value=0.3753453856869
result=""
while(value<1):
value*=2
if(value>=1):
value-=1
result+=str(1)
else:
result+=str(0)
if len(result) == ENOUGH_PRECISION:
break
print(result)
输出:
01100000000101101010