【问题标题】:The code works incorrectly and displays incomprehensible numbers:该代码工作不正确并显示难以理解的数字:
【发布时间】:2021-10-31 00:38:34
【问题描述】:

代码运行不正确并显示难以理解的数字: 3.612432554629948e + 76 显示难以理解的值,应该是这样的: 并且应该输出: 以大数为例: 十六进制:8459f630cd86ddfa329b3d13d5217d45df1d5e9a56a63f6a3d7ab8b794c35c12 十二月:59864244547079690871082685810675850360550404961977540588162601013229404773394

# Covert a file with lines of hex values in "hex.txt" to decimal
# values and write to "dec.txt"

# NOTE: This program only handles Value errors and replaces them
# with the string XXXXX, no other error handling is performed  

HEXLIST_FILENAME = "hex.txt"
DECLIST_FILENAME = "dec.txt"

def loadHex():
    """
    Returns a list of Hex strings from a file
    
    """
    hexList = []
    print ("Loading hex list from file...")
    try:
        inFile = open(HEXLIST_FILENAME, 'r')
    except IOError:
        print('No such file "hex.txt"')
        #more error handeling here
    for line in inFile:
        hexList.append(line.strip().upper())
    print (len(hexList)), "Numbers loaded."
    return hexList

def hexToDec(hexString):
    """
    Takes in a string representing a hex value
    
    Returns a decimal number string
    """
    try:
        i=int(hexString,16)
    except ValueError:
        print('Oops! There was an invalid number in hex.txt...')
        print('Invalid number replaced with XXXXX')
        i='XXXXX'
    return str(i/float(2**21))

def exportDec(decList):
    """


    """
    outFile=open(DECLIST_FILENAME,'w')
    for num in decList:
        outFile.write(num+"\n")

    outFile.close()
    print ("Success! Decimal numbers written to dec.txt")


decList = []
hexVals=loadHex()
for hexnum in hexVals:
    decList.append(hexToDec(hexnum))

exportDec(decList)

s=input()('Press Enter to exit...')

【问题讨论】:

    标签: python-3.x hex decimal


    【解决方案1】:

    不确定为什么在 hexToDec 方法中将转换后的值除以 2**21:

    return str(i/float(2**21))
    

    除法是不必要的,如果你只是,你会得到正确的输出

    return str(i)
    

    直接来自您的 hexToDec 方法。

    【讨论】:

    • 我现在检查它给出了 1.0 1.0 1.0
    • 谢谢 Niraj Gupta 一切顺利
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2014-02-03
    • 2015-07-11
    相关资源
    最近更新 更多