【问题标题】:Is there a way to make this code less taxing on the computer? [duplicate]有没有办法让这段代码在计算机上的负担更少? [复制]
【发布时间】:2020-09-21 08:21:26
【问题描述】:

我有一些 python 可以将十进制数字转换为十六进制,但是,我的计算机需要很长时间并且在代码完成之前就关闭了。有没有办法将此代码压缩到更少的行?我已经下载了 Python 3.8.3。 python 在纯文本(但 .py)文件中,我通过 macOS High Sierra (v10.13.6) 上的终端运行它。

import math

dec = float(input("Decimal: "))

while(math.floor(dec/16) >= 0):
  x = "Hex: "
  rem = dec/16 - math.floor(dec/16)
  myHex = rem*16
  if myHex > 9 :
    if myHex == 10 :
      x += "A"

    if myHex == 11 :
      x += "B"

    if myHex == 12 :
      x += "C"

    if myHex == 13 :
      x += "D"

    if myHex == 14 :
      x += "E"

    if myHex == 15 :
      x += "F"

  else :
    x += str(myHex)  

print (x)

【问题讨论】:

  • 你知道内置的hex吧?
  • 无论如何,math.floor(dec/16) >= 0 永远是True,因此是无限循环
  • @DeepSpace 你知道十六进制只会接受整数,对吧?
  • 是的,这就是目标。感谢您的帮助
  • 所以,我应该把它改成 '>' 而不是 '>=' 对吧?

标签: python compiler-errors


【解决方案1】:

您可以只使用struct 模块:

import struct

f = float(input("> "))
print(hex(struct.unpack('<I', struct.pack('<f', f))[0]))

输入:

> 234.345

输出:

0x436a5852

【讨论】:

  • 我不知道它是如何工作的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 2018-10-01
  • 1970-01-01
  • 2021-02-01
相关资源
最近更新 更多