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 = n 14 s_float = ‘‘ 15 total_int, total_float = 0, 0 16 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 - 1 22 total_int = total_int + int(c)*pow(2,li) 23 24 lf = 0 25 for c in s_float: 26 lf = lf + 1 27 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_int 35 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 % 2 41 t_int = t_int + str(a) 42 num_int = num_int//2 43 44 while num_float != 0: 45 b = num_float*2 46 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 = 1 58 for c in n: 59 if c != ‘1‘ and c != ‘0‘: 60 print("输入错误,请重新输入") 61 flag = 0 62 break 63 if flag: 64 break 65 pre = int(input("请输入保留几位小数:")) 66 bTod(n,pre) 67 elif a == ‘1‘: 68 while True: 69 n = input("请输入一个十进制数:") 70 flag = 1 71 for c in n: 72 if c <= ‘0‘ or c >= ‘9‘: 73 print("输入错误,请重新输入") 74 flag = 0 75 break 76 if flag: 77 break 78 pre = int(input("请输入保留几位小数:")) 79 dTob(n,pre) 80 else: 81 print("无效输入")
原文地址:https://www.cnblogs.com/zcl843264327/p/9348199.html
时间: 2024-10-16 19:17:55