【问题标题】:How did I create an infinite loop when trying to convert bases尝试转换基数时如何创建无限循环
【发布时间】: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_numnew_base 永远不会在循环中更改它们的值,因此该除法的结果将始终产生相同的数字。只要这个除法的结果不为零,循环就会继续,因为quotient 将始终具有相同的非零值。
  • 另外,return 退出函数;函数的最后两行永远不会执行。
  • 出于效率原因,您应该将剩余部分追加到列表中,然后在返回之前反转列表。 (或者代替list,使用collections.deque,它支持高效的前置。)
  • @chepner 谢谢!虽然对于最后几行,我不需要在打印之前返回值吗?
  • 否;如果您从函数打印,则根本不需要返回它。但是如果你just返回值,然后让调用者if想要打印它,这个函数会更灵活。

标签: python infinite-loop base base-conversion


【解决方案1】:

你不断将dec_num 除以new_base,它永远不会改变。您的代码将在一次迭代后退出,或者永远不会退出,具体取决于 newbase 是否除以 dec_num。这个想法是你总是在每次迭代中划分当前的。另外,您可以使用divmod 同时获取商和余数。

quotient = dec_num
while not quotient:
    quotient, remainder = divmod(quotient, new_base)
    ...

【讨论】:

    【解决方案2】:

    我猜是因为你在while循环之前将商设置为-1,所以它不会改变并且总是不同于0,从而导致无限循环。顺便说一句,我也是个菜鸟。我希望我是对的并有所帮助。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多