gpt4 book ai didi

python - 陷入无限循环

转载 作者:太空宇宙 更新时间:2023-11-04 07:00:58 25 4
gpt4 key购买 nike

我正在尝试用 Python 编写一个程序,将十进制数转换为等效的十六进制数。当我运行该程序时,它为我提供了正确的转换,但它在无限循环中运行。我不确定无限循环到底发生在哪里。这是我的代码:

def remainderToHex(remainder):
if remainder <= 9:
remainder = str (remainder)
elif remainder == 10:
remainder = "A"
elif remainder == 11:
remainder = "B"
elif remainder == 12:
remainder = "C"
elif remainder == 13:
remainder = "D"
elif remainder == 14:
remainder = "E"
elif remainder == 15:
remainder = "F"
return remainder

def decToHex(decNum):
hexNum = ""
quotient = decNum
divNum=16
if quotient == 0:
hexNum = 0
while quotient > 0:
remainder = quotient % divNum
convertedHex= remainderToHex(remainder)
quotient = int (quotient / divNum)
hexNum = convertedHex + hexNum
return hexNum

def main():
decNum=int(raw_input("Please enter a non negative number OR enter -1 to quit: "))
while decNum >= -1:
hexNumber = decToHex(decNum)
print decNum, "convered to hex is: ", hexNumber
print "Thank you"

谢谢!

最佳答案

您正在执行 while decNum >= -1。假设用户没有立即输入 -1,那么 decNum永远变得小于 -1,while 循环将永远不会结束。相反,使用 if 语句。如果用户输入 -1,则结束该过程,否则进行转换。

正如已经指出的那样,>= 应该是 >

关于python - 陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28244060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com