Python程式將浮點數轉換為二進位制數


在本文中,我們將介紹如何將浮點值轉換為二進位制數。二進位制數使用兩個數字,0 和 1。也稱為基數 2 數制,二進位制數中的每個位置表示基數 (2) 的 0 次方。二進位制數中的最後一個位置表示基數 (2) 的 x 次方。

首先,我們從浮點值中獲取整數部分並將其轉換為二進位制數,然後獲取小數部分並將其轉換為二進位制形式,最後將這兩部分結合起來。

假設我們有以下浮點數:

22.625

將十進位制數 22 轉換為二進位制數 10110。將十進位制數 0.625 轉換為二進位制數 0.101。組合整數和小數部分,得到以下輸出:

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

更新日期:2022 年 8 月 12 日

3K+ 瀏覽量

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告