Python 含小數的十、二進位相互轉換問題

來源:互聯網
上載者:User

標籤:lag   除法   color   類型   逆序輸出   inpu   取整   size   float   

 1 ‘‘‘ 2 二進位->十進位:bTod 3     整數部分:a乘以2的n次方(n:a後面的整數位元) 4     小數部分:a乘以2的-n次方(n:a是小數點後幾位) 5 十進位->二進位dTob 6     整數部分:短除法(除二取餘法,逆序輸出) 7     小數部分:乘二取整法,0.……正向輸出所得 8      9 函數中形參n為字串類型10 ‘‘‘11 #二進位->十進位12 def bTod(n, pre = 4):13     s_int = n14     s_float = ‘‘15     total_int, total_float = 0, 016     if ‘.‘ in n:17         s_int, s_float = n.split(‘.‘)18         19     li = len(s_int)20     for c in s_int:21         li = li - 122         total_int = total_int + int(c)*pow(2,li)23         24     lf = 025     for c in s_float:26         lf = lf + 127         total_float = total_float +int(c)*pow(2,-lf)28         29     print("{}轉化為十進位是{:.{}f}".format(n,total_int + total_float, pre))30 31 #十進位->二進位32 def dTob(n, pre = 4):33     num_int = int(eval(n))34     num_float = eval(n) - num_int35     t_int, t_float = ‘‘, ‘‘36     if ‘.‘ in n:37         s_int, s_float = n.split(‘.‘)38 39     while num_int!= 0:40         a = num_int % 241         t_int = t_int + str(a)42         num_int = num_int//243 44     while num_float != 0:45         b = num_float*246         t_float = t_float + str(int(b))47         num_float = b - int(b)48  49     #print(t_int[::-1] + ‘.‘ + t_float[:])50     print("{}轉化為二進位是{:.{}f}".format(n,eval(t_int[::-1] + ‘.‘ + t_float[:]), pre))51 52 53 a = input("請輸入0(轉化為十進位)或輸入1(轉化為二進位):")54 if a == ‘0‘:55     while True:56         n = input("請輸入一個位元:")57         flag = 158         for c in n:59             if c != ‘1‘ and c != ‘0‘:60                 print("輸入錯誤,請重新輸入")61                 flag = 062                 break63         if flag:64             break65     pre = int(input("請輸入保留幾位小數:"))66     bTod(n,pre)67 elif a == ‘1‘:68     while True:69         n = input("請輸入一個十進位數:")70         flag = 171         for c in n:72             if c <= ‘0‘ or c >= ‘9‘:73                 print("輸入錯誤,請重新輸入")74                 flag = 075                 break76         if flag:77             break78     pre = int(input("請輸入保留幾位小數:"))79     dTob(n,pre)80 else:81     print("無效輸入")

 

Python 含小數的十、二進位相互轉換問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.