欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

包含小数的二进制十进制转换

程序员文章站 2022-07-15 09:58:05
...
import math
num = input("请输入要转换的数")
judge = int(input("次数为二进制数请输1,此数为十进制数请输2:"))
DEC = 0
BIN = float(0)
if judge == 1:
    location = num.find(".")
    for i in range(0, len(num)):
        if i < location:  # 整数运算
            DEC += int(num[location-(i+1)])*pow(2, i)
        if i > location:  # 小数运算
            DEC += int(num[len(num) - (i + 1)]) * pow(2, location - i)
    print(num + "转换为十进制数为:", DEC)
if judge == 2:  # 使用2的二次幂的方法。
    DEC = float(num)
    i = 0
    saveI = []
    saveF = []
    #整数部分
    while DEC >= 2:
        if pow(2, i) > DEC:
            saveI.append(i-1)
            DEC -= pow(2, i-1)
            i = 0
        i += 1
    if int(DEC) > 0:
        saveI.append(0)
    #小数部分
    DEC = float(num)
    DEC = float(DEC) - int(float(num))
    while DEC < 1 and DEC != 0:
        i -= 1
        if pow(2, i) <= DEC:
            saveF.append(i)
            DEC -= pow(2, i)
            i = 0
    for i in range(0, len(saveI)):
        BIN += pow(10, saveI[i])
    for i in range(0, len(saveF)):
        BIN += pow(10, saveF[i])
    print(num, "转换为二进制数为:", BIN)

写作业时顺道写的 

 

相关标签: python