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


八進位制數使用八位數字,0,1,2,3,4,5,6,7。也稱為基數為 8 的數字系統。八進位制數中的每個位置表示基數(8)的 0 次冪。八進位制數中的最後位置表示基數(8)的 x 次冪。

十進位制數系統以 10 為基數,因為它使用了 0 到 9 這十個數字。在十進位制數系統中,小數點左邊的連續位置依次表示個位、十位、百位、千位,依此類推。

給定一個浮點十進位制值並輸入小數位數,我們的任務是將其轉換為八進位制形式。假設我們有以下浮點數 -

6.89

首先,我們從浮點值中取出整數部分並將其轉換為八進位制,然後取出小數部分並將其轉換為八進位制形式,最後將兩者合併。考慮小數點後 12 位。輸出將為 -

6.707534121727

透過獲取使用者輸入將浮點數轉換為八進位制數

示例

def float_convert_octal(my_number, places = 3): my_whole, my_dec = str(my_number).split(".") my_whole = int(my_whole) my_dec = int (my_dec) res = oct(my_whole).lstrip("0o") + "." for x in range(places): my_whole, my_dec = str((decimal_converter(my_dec)) * 8).split(".") my_dec = int(my_dec) res += my_whole return res def decimal_converter(num): while num > 1: num /= 10 return num n = input("Enter the floating point value : \n") p = int(input("Enter the number of decimal places of the result : \n")) print(float_convert_octal(n, places = p))

輸出

Enter the floating point value :
6.89
Enter the number of decimal places of the result :
12
6.707534121727

更新日期:12-8-2022

532 次檢視

開啟 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.