给定一个浮点值并输入小数位数,我们的任务是将其转换为二进制形式。
首先,我们从浮点值中取整数部分,然后将其转换为二进制,然后取小数部分,并将其转换为二进制形式,最后将两者合并。
The floating point value is 22.625 Convert decimal 22 to binary 10110. Convert decimal 0.625 to binary 0.101. Combine integer and fraction to obtain binary 10110.101.
def floatoctal_convert(my_number, places = 3): my_whole, my_dec = str(my_number).split(".") my_whole = int(my_whole) my_dec = int (my_dec) res = bin(my_whole).lstrip("0b") + "." for x in range(places): my_whole, my_dec = str((my_decimal_converter(my_dec)) * 8).split(".") my_dec = int(my_dec) res += my_whole return res def my_decimal_converter(num): while num > 1: num /= 10 return num # Driver Code n = input("Enter floating point value : \n") p = int(input("Enter the number of decimal places of the result : \n")) print(floatoctal_convert(n, places = p))
输出结果
Enter floating point value : 2.34 Enter the number of decimal places of the result : 3 10.256