大佬們看一下那有不足,皮皮在此謝過了。this
def bTod (a,p=4): ''' bTod(...) bTod(string,integer) input: String only contains numeric characters or points or minus sign, the string represents a binary number.And the integer is used to determine the accuracy of the output data. process: Converts the binary number that this string represents to a decimal number . output: Print the result(decimal number) that determines the accuracy. ''' p=int(p) sign='' if a[0]=='-': sign=a[0] a=a[1:] ithpower=0 intsum=0 floatsum=0 for c in a: if c not in ('1','0','.'): print("輸入的數值不是二進制數") return 0 if a.count(".")>1: print("輸入錯誤") return 0 elif a.count(".")==1: cut=a.split(".") pointbefore=cut[0] pointbefore=pointbefore[::-1] pointafter=cut[1] else : pointbefore=a[::-1] pointafter="0" for c in pointbefore: intsum=intsum+ int(c)*(2**ithpower) ithpower=ithpower+1 ithpower=-1 for c in pointafter: floatsum=floatsum+int(c)*(2**ithpower) ithpower=ithpower-1 result=intsum+floatsum print("二進制數{}轉變成十進制數保留{}位小數的結果是{}{:.{}f}" .format(a,p,sign,result,p)) def dTob(a,p=4): ''' bTod(...) bTod(string,integer) input: String only contains numeric characters or points or minus sign, the string represents a decimal number.And the integer is used to determine the accuracy of the output data. process: Converts the decimal number that this string represents to a binary number . output: Print the result(binary number) that determines the accuracy. ''' p=int(p) times=0 sign='' if a[0]=='-': sign=a[0] a=a[1:] for c in a: if (c<'0' or c>'9') and c!='.': print("輸入錯誤") return 0 if a.count(".")>1: print("輸入錯誤") return 0 elif a.count('.')==1: cut=a.split(".") pointafter=float("0."+cut[1]) auto=bin(int(cut[0])) intsum=auto[2:] floatsum='' times=0 while pointafter : t=pointafter*2 if t<1: floatsum=floatsum+'0' pointafter=pointafter*2 times=times+1 else: floatsum=floatsum+'1' pointafter=t-1 times=times+1 if times >500: print("轉化後的小數爲無限小數") break if len(floatsum)>p: floatsum=floatsum[:p] elif len(floatsum)<p: floatsum=floatsum+'0'*(p-len(floatsum)) else: floatsum=floatsum result=intsum+'.'+floatsum print("十進制數{}轉化爲二進制數保留{}位小數的結果是{}{}" .format(a,p,sign,result)) else : p=int(p) auto=bin(int(a)) result=auto[2:]+'.'+'0'*p print("十進制數{}轉化爲二進制數保留{}位小數的結果是{}{}" .format(a,p,sign,result)) print("請在輸入數字前加上數字類型(十進制爲d、二進制爲b,默認爲十進制轉二進制,默認精度爲小數點後四位),q退出程序") while 1: n=input("請輸入要轉換的內容:") if n=='q': print("程序退出") break else: pole=1 while pole : s=input("請輸入精度:") if s=='': s=4 break for c in s: if '0'<=c<='9': pole=0 else: print("精度輸入錯誤") pole=1 break if n=='': print("輸入錯誤") elif n[0]=='d': dTob(n[1:],s) elif '0' <=n[0]<='9' or n[0]=='-': dTob(n,s) elif n[0]=='b': bTod(n[1:],s) else: print("輸入錯誤")