[英]How do i call a recursive function in this python program where I am supposed to convert decimal numbers to hexadecimal?
x=""
def main():
Decimal=int(input("Enter a decimal value"))
print (DecimaltoHexa(Decimal))
def HexaLetters(Hexa):
这是十六进制在这里导入大于9的数字的地方
if Hexa==10:
return "A"
elif Hexa==11:
return "B"
elif Hexa==12:
return "C"
elif Hexa==13:
return "D"
elif Hexa==14:
return "E"
elif Hexa==15:
return "F"
def DecimaltoHexa(Decimal):
这里需要帮助,因为这是程序的主体,我不能使用循环,因为我必须添加一个递归函数,但是我需要这样做。
global x
y=0
LastDigit=0
Hexa=Decimal%16
if Hexa>9:
Hexa=HexaLetters(Hexa)
Decimal=int(Decimal/16)
if Decimal<16:
y=-1
LastDigit=Decimal
x=str(Hexa)+x
final=str(LastDigit)+x
return (final)
DecimaltoHexa(Decimal)
main()
按照以下方式修改您的递归方法,以将十进制转换为六进制
def main():
Decimal=int(input("Enter a decimal value"))
print (DecimaltoHexa(Decimal, ""))
def HexaLetters(Hexa):
if Hexa == 10:
return "A"
elif Hexa == 11:
return "B"
elif Hexa == 12:
return "C"
elif Hexa == 13:
return "D"
elif Hexa == 14:
return "E"
elif Hexa == 15:
return "F"
def DecimaltoHexa(Decimal, prev_hexa):
remainder = Decimal % 16
remaining_Decimal = Decimal // 16
hexa_char = str(remainder)
if remainder > 9:
hexa_char = HexaLetters(remainder)
current_hexa = hexa_char + prev_hexa
if remaining_Decimal != 0:
current_hexa = DecimaltoHexa(remaining_Decimal, current_hexa)
return current_hexa
main()
但是,如果您想要更简洁的解决方案,则可以使用以下实现-
hexa_chars = map(str, range(10)) + ["A", "B", "C", "D", "E", "F"]
def int_to_hexa(decimal, curr_hexa):
rem = decimal % 16
rem_decimal = decimal // 16
curr_hexa = hexa_chars[rem] + curr_hexa
if rem_decimal:
curr_hexa = int_to_hexa(rem_decimal, curr_hexa)
return curr_hexa
if __name__ == '__main__':
dec = input()
hexa_num = ""
hexa_num = int_to_hexa(dec, hexa_num)
print(hexa_num)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.