此函数将十进制转换为十六进制,但它只打印两位数字。我如何让它打印更多?
This function converts a decimal to a hexadecimal, however it only prints two digits. How do I get it to print more?
这只需要最多 255 个数字,因此它只打印两位数。为什么它只打印两位数?看起来 while 循环只有 运行 一次或类似的东西。根据我的想法,它应该 运行 一次或两次。 5368 的十六进制应该是 14F8,函数接近了,但是正如您所看到的,它只打印了 1 和 4,而不是 F 或 8。另外,我怎样才能让它转换为浮点数?
import math
def hexConvert(dec):
while(math.floor(dec/16) > 0):
x = ""
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 :
myHex = str(int(myHex))
x += myHex
dec = math.floor(dec/16)
remainder = dec/16 - math.floor(dec/16)
myHex2 = remainder*16
if myHex2 > 9 :
if myHex2 == 10 :
x += "A"
if myHex2 == 11 :
x += "B"
if myHex2 == 12 :
x += "C"
if myHex2 == 13 :
x += "D"
if myHex2 == 14 :
x += "E"
if myHex2 == 15 :
x += "F"
else :
myHex2 = str(int(myHex2))
x += str(myHex2)
x = x[::-1]
print ("Hex: " + x)
hexConvert(5368)
您需要将 x
的赋值移动到 while 循环之外。在函数定义之后立即使用 x = ""
定义 x,然后删除重新定义。前四行应为:
import math
def hexConvert(dec):
x = ""
while(math.floor(dec/16) > 0):
rem = dec/16 - math.floor(dec/16)
截至目前,您每两位数字清除一次 X 值,导致您丢失了应该位于末尾的 F8。
这只需要最多 255 个数字,因此它只打印两位数。为什么它只打印两位数?看起来 while 循环只有 运行 一次或类似的东西。根据我的想法,它应该 运行 一次或两次。 5368 的十六进制应该是 14F8,函数接近了,但是正如您所看到的,它只打印了 1 和 4,而不是 F 或 8。另外,我怎样才能让它转换为浮点数?
import math
def hexConvert(dec):
while(math.floor(dec/16) > 0):
x = ""
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 :
myHex = str(int(myHex))
x += myHex
dec = math.floor(dec/16)
remainder = dec/16 - math.floor(dec/16)
myHex2 = remainder*16
if myHex2 > 9 :
if myHex2 == 10 :
x += "A"
if myHex2 == 11 :
x += "B"
if myHex2 == 12 :
x += "C"
if myHex2 == 13 :
x += "D"
if myHex2 == 14 :
x += "E"
if myHex2 == 15 :
x += "F"
else :
myHex2 = str(int(myHex2))
x += str(myHex2)
x = x[::-1]
print ("Hex: " + x)
hexConvert(5368)
您需要将 x
的赋值移动到 while 循环之外。在函数定义之后立即使用 x = ""
定义 x,然后删除重新定义。前四行应为:
import math
def hexConvert(dec):
x = ""
while(math.floor(dec/16) > 0):
rem = dec/16 - math.floor(dec/16)
截至目前,您每两位数字清除一次 X 值,导致您丢失了应该位于末尾的 F8。