【问题标题】:How to best update while loop for finding the digital root?如何最好地更新while循环以找到数字根?
【发布时间】:2021-03-17 22:01:06
【问题描述】:

我正在尝试创建一个函数来迭代某个数字的数字并重复查找其数字的总和,直到数字中只剩下一个数字。

我想用一个while循环来做这个,但循环永远不会结束。我不明白为什么我的更新行 n_s = str(total) 不起作用

def digital_root(n):
    n_s = str(n)
    
    total = 0
    
    while len(n_s) != 1:
        for digit in n_s:
            total += int(digit)
        n_s = str(total)
    return total

【问题讨论】:

    标签: python loops


    【解决方案1】:

    您没有重置 total 的值,因此使用的是最后一个循环的值,而不是从 0 开始。

    def digital_root(n):
        n_s = str(n)
    
        while len(n_s) != 1:
            total = 0
            for digit in n_s:
                total += int(digit)
            n_s = str(total)
        return total
    

    【讨论】:

      猜你喜欢
      • 2016-06-13
      • 2013-12-26
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多