我编写了一个程序来将十进制转换为十六进制,这相当于 python 中的 hex() 函数。程序打印正确的值直到'2559'。如何为较大的数字获取正确的十六进制值。代码无法从 2600 十进制值中给出正确的十六进制表示。这是我的代码:
#########################################
#Decimal to Hexadecimal Conversion #
#########################################
def DectoHex(n):
if n <= 16:
return n
elif n>16:
if n%16 == 10:
x = 'A'
elif n%16 == 11:
x = 'B'
elif n%16 == 12:
x = 'C'
elif n%16 == 13:
x = 'D'
elif n%16 == 14:
x ='E'
elif n%16 == 15:
x = 'F'
else:
x = n%16
print x
n = n/16
print n
if n == 10:
n = 'A'
elif n == 11:
n = 'B'
elif n == 12:
n = 'C'
elif n == 13:
n = 'D'
elif n == 14:
n ='E'
elif n == 15:
n = 'F'
elif n>=16:
if n%16 == 10:
n = str(n/16) + 'A'
elif n%16 == 11:
n = str(n/16) + 'B'
elif n%16 == 12:
n = str(n/16) + 'C'
elif n%16 == 13:
n = str(n/16) + 'D'
elif n%16 == 14:
n = str(n/16) + 'E'
elif n%16 == 15:
n = str(n/16) + 'F'
else:
n = str(n/16) + str(n%16)
print n
return str(n) + str(x)
print "Would you like to continue:"
print "Enter 'Y' to continue, 'N' to quit"
Str = str (raw_input("> "))
while True:
if Str == 'Y':
print "Enter a decimal number:"
dec = int (raw_input("> "))
Hex = DectoHex(dec)
print "The number in base 16 is:", Hex
print "Enter 'Y' to continue, 'N' to quit"
Str = str (raw_input("> "))
elif Str == 'N':
print "Good Bye!"
break
else:
print "Plesae Enter 'Y' or 'N'"
Str = str (raw_input("> "))