【发布时间】:2020-10-14 17:22:42
【问题描述】:
我正在尝试编写将采用任何十进制值然后将其转换为任何输入基数的代码。
我创建了一个无限循环,并阅读了建议的类似问题,但我无法解决。
任何帮助都将不胜感激,我是一个主要的 python 新秀(显然)。
decimal = int(input("Enter a decimal number to be converted: "))
new_base = int(input("Enter the base you wish to convert to: "))
def base_conversion(decimal, new_base):
output = []
quotient = -1
while quotient != 0:
remainder = decimal % new_base
quotient = int(decimal / new_base)
output.insert(0, remainder)
return output
result = output
print(result)
base_conversion(decimal, new_base)
【问题讨论】:
-
quotient在循环的每次迭代中都被分配了dec_num / new_base的值。dec_num和new_base永远不会在循环中更改它们的值,因此该除法的结果将始终产生相同的数字。只要这个除法的结果不为零,循环就会继续,因为quotient将始终具有相同的非零值。 -
另外,
return退出函数;函数的最后两行永远不会执行。 -
出于效率原因,您应该将剩余部分追加到列表中,然后在返回之前反转列表。 (或者代替
list,使用collections.deque,它支持高效的前置。) -
@chepner 谢谢!虽然对于最后几行,我不需要在打印之前返回值吗?
-
否;如果您从函数打印,则根本不需要返回它。但是如果你just返回值,然后让调用者if想要打印它,这个函数会更灵活。
标签: python infinite-loop base base-conversion