import struct
def print_binary(number_string):
bin = ""
if "." in number_string:
number_string = float(number_string)
bin += bin(struct.unpack('!i',struct.pack('!f', number_string)))
else:
num = int(number_string)
bin += "{0:b}".format(num)
print(bin)
我在将带小数的数字转换为二进制(我的if语句)时遇到问题
test_values = "0 1234 -1234 12.4 0.6 -12.4 -0.6 -1234567890.123456789".split()
当它达到12.4时出现错误
答案 0 :(得分:0)
我使用了递归。但是这里的某些值可能存在递归限制。
这是我手工使用的方法。
Fractional Part = .6875 in base 10
.6875*2 equals 1.375 whole number is 1
.375*2 equals 0.75 whole number is 0
.75*2 equals 1.5 whole number is 1
.5*2 equals 1.0 whole number is 1
Hence .6875D = .1011 in base 2
然而,想想12.4的价值。它将永远存在!
.4*2 = .8
.8*2 = 1.6
.6*2 = .2
.2*2 = .4
... and so on
所以我们必须在递归计算中设置一个限制。我做了10.虽然这听起来不是很多,但看看它有多精确。
我输入的12.4返回1100.0110011001,等于12.3994140625
非常接近,随意玩这个数字,取其上限等等。
以下是代码:
def get_integer_part(pre_decimal_string):
# special case of negative 0 being a prefix "-0.6"
if pre_decimal_string == "-0":
return "-0"
else:
num = int(pre_decimal_string)
return "{0:b}".format(num)
def get_decimal_part(post_decimal_string, string_builder, recurse):
recurse += 1
post_decimal_value = float("." + post_decimal_string)
if post_decimal_value == 0 or recurse > 10:
return string_builder
else:
temp_mult_str = str(post_decimal_value * 2)
temp_mult_split = temp_mult_str.split(".")
string_builder += temp_mult_split[0]
return get_decimal_part(temp_mult_split[1], string_builder, recurse)
def print_binary(number_string):
# handle case of no preceding 0 ".3" or
if number_string[0] == ".":
number_string = "0" + number_string
# handle case of no preceding 0 and is negative
if number_string[0:2] == "-.":
number_string = "-0" + number_string[1:]
if "." in number_string:
str_split = number_string.split(".")
print(get_integer_part(str_split[0]) + "." + str(get_decimal_part(str_split[1], "", 0)))
else:
print(get_integer_part(number_string))
test_values = "0 1234 -1234 12.4 0.6 -12.4 -0.6 -1234567890.123456789".split()
print(test_values)
for each in test_values:
print_binary(each)
# special cases
print_binary("-.7")
print_binary(".67")
这是最终输出:
0
10011010010
-10011010010
1100.0110011001
0.1001100110
-1100.0110011001
-0.1001100110
-1001001100101100000001011010010.0001111110
-0.1011001100
0.1010101110
虽然我会以不同的方式做到这一点,但我尽可能地保留了您的代码和格式,以便您最容易学习。