如何将数字的各位数字之和返回为整数?
这是我需要写的内容:
- 一个叫做 countDigits 的函数,它会接收一个整数作为参数,并返回这个整数的各个数字之和(你必须使用 for 循环)。比如,数字 123 的各位数字相加就是 6(1 + 2 + 3)。
一个主函数,它会从 1 开始数,直到所有数字的总位数超过 1,000,000 为止。所以,如果你想计算数字 5 的总位数,你需要这样加:
- 1 = 1
- 2 = 2 + 1
- 3 = 3 + 3
- 4 = 6 + 4
- 5 = 10 + 5,所以总位数是 15。
你的程序会在位数超过 1,000,000 之前,打印出数字和对应的位数。这用 while 循环来做是最简单的。
我已经写好了 countDigits 函数的代码,如下:
def countDigits():
value=int(input('Enter Integer: '))
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
print(total)
不过,我在写主函数时遇到了困难。有没有人能给我一些建议?
编辑
这是我修改后的 countDigits 函数:
def countDigits(value):
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
print(total)
2 个回答
1
正如@Blorgbeard在评论中提到的,把countDigits
改成可以接收一个整数作为输入。同时,要让它返回总数。
在主函数里,读取输入,调用countDigits
,然后在一个循环里不断加总,直到总数超过1,000,000为止。
def countDigits(value):
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
return total
grandTotal = 0
while ( grandTotal < 1000000 ):
value=int(input('Enter Integer: '))
grandTotal += countDigits(value)
2
一句话解决:
factorial_digit_sum = lambda x: sum( sum(map(int, str(a))) for a in range(1,x+1) )
如果你真的写出这样的代码,Guido会来找你的。不过,把它当成一个有趣的脑筋急转弯来玩还挺好。
要真正解决这个问题:
def countDigits(number):
return sum(map(int, str(number)))
def main():
total = 0
count = 1
while total <= 1000000:
total += countDigits(count)
total -= countDigits(count) # you want the number BEFORE it hits 1000000
print("Summing the digits of {}! yields {}".format(count, total))
main()
你代码中的问题是你的 countDigits
函数需要用户输入。你应该把它改成接受一个整数作为参数。而且它是用 print
来输出结果,而不是用 return
来返回结果。