Python十六进制转十进制代码输出科学计数法结果异常如何修复?
问题根因
- 核心转换逻辑错误:
hexToDec函数中多余执行了i/float(2**21)操作,你需求是直接将十六进制转十进制整数,该除法逻辑完全不符合需求。同时超大整数转float会出现精度丢失,且自动用科学计数法格式化输出,就是你看到3.612432554629948e+76这类结果的原因。 - 语法错误:代码最后一行的等待输入逻辑写法错误,运行到此处会抛出 TypeError 异常。
- 异常处理漏洞:如果
hex.txt不存在,捕获IOError后没有终止程序,后续遍历未定义的inFile变量会直接报错。
修复方案
- 删除
hexToDec中多余的除法逻辑,直接返回十六进制转成的整数字符串即可 - 修正最后一行的输入提示代码
- 补全文件打开失败后的退出逻辑,改用
with上下文管理器优化文件操作,避免资源泄漏
完整修复后代码
# 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: with open(HEXLIST_FILENAME, 'r') as inFile: for line in inFile: hexList.append(line.strip().upper()) except IOError: print('No such file "hex.txt"') exit(1) 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') return 'XXXXX' return str(i) def exportDec(decList): """ Writes decimal list to output file """ with open(DECLIST_FILENAME, 'w') as outFile: for num in decList: outFile.write(num+"\n") print ("Success! Decimal numbers written to dec.txt") decList = [] hexVals = loadHex() for hexnum in hexVals: decList.append(hexToDec(hexnum)) exportDec(decList) input('Press Enter to exit...')
内容的提问来源于stack exchange,提问作者kamburishka
相关产品推荐
相关产品推荐

