Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我是python的初学者,试图解决这个问题输入=777输出=7+;7+;7=21>&燃气轮机;2+;1=3#直至一位数;它进入无限循环_Python_String_Loops_While Loop_Integer - Fatal编程技术网

我是python的初学者,试图解决这个问题输入=777输出=7+;7+;7=21>&燃气轮机;2+;1=3#直至一位数;它进入无限循环

我是python的初学者,试图解决这个问题输入=777输出=7+;7+;7=21>&燃气轮机;2+;1=3#直至一位数;它进入无限循环,python,string,loops,while-loop,integer,Python,String,Loops,While Loop,Integer,您可以尝试以下方法: def sum_of_digits(n): a = str(n) c = 0 while len(a)>1: for i in range(len(a)): c+=int(a[i]) a = str(c) #return c print(c) sum_of_digits(777) 正如MisterMiyagi所说,您的程序非常

您可以尝试以下方法:

def  sum_of_digits(n):
    a = str(n)
    c = 0

    while len(a)>1:
        for i in range(len(a)):
            c+=int(a[i])
        a = str(c)
        #return c
        print(c)            

sum_of_digits(777)

正如MisterMiyagi所说,您的程序非常接近您所需要的,在for循环之后立即将c重置为0。它进入无限循环,因为你的“c”只是在添加数字,而“a”检索那个一直在增长的数字。。。
for循环之后的C=0将完成这项任务,您需要在每次迭代之前或之后重置计数器变量
C
。在第一次迭代中,777变为
7+7+7=21
,您将其存储在
c
中。然后将
c
(即
21
)转换为字符串并存储到
a

现阶段:
c=21和a=“21”(字符串)

在这之后,您必须设置
c=0
,因为在下一次迭代中,我们将使用
c+=int(a[i])
再次计算
21
的总和,即
2+1=3
。如果不重置
c
,则
c
的上一个值将添加到
3
,该值为
21+3=24
(如果不设置c=0,则从第一次迭代开始为21),因此它将永远增加,并创建一个无限循环

def  sum_of_digits(n):
  if(len(n) == 1):
    return n
  return int(n[0])+int(sum_of_digits(n[1:len(n)]))
    

sum = "00"
param = "0123654789"
while (len(str(sum)) != 1):
  
  sum = sum_of_digits(param)
  param = str(sum)
  
  
  
print(sum)

    

您从未将
c
重置为0。
def  sum_of_digits(n):
    a = str(n)
    c = 0

    while len(a)>1:
        c = 0
        
        for i in range(len(a)):
            c+=int(a[i])
        a = str(c)
        #return c
        print(c)    
        
    return c
    
    
sum_of_digits(777)