Python程序:无需递归求解数字各位之和
当需要求解数字各位之和而不使用递归方法时,可以使用‘%’运算符、‘+’运算符和‘//’运算符。
下面是一个演示:
示例
def sum_of_digits(my_num): sum_val = 0 while (my_num != 0): sum_val = sum_val + (my_num % 10) my_num = my_num//10 return sum_val my_num = 12345671 print("The number is : ") print(my_num) print("The method to calculate sum of digits is being called...") print("The sum of " +str(my_num) + " is : ") print(sum_of_digits(my_num))
输出
The number is : 12345671 The method to calculate sum of digits is being called... The sum of 12345671 is : 29
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
解释
- 定义了一个名为‘sum_of_digits’的方法,它接收一个数字作为参数。
- 初始将sum赋值为0。
- 将数字除以10,并将得到的余数添加到sum中。
- 将数字再次向下取整除以10,并将结果赋值给数字本身。
- 函数返回sum值作为输出。
- 定义一个数字,并在控制台上显示。
- 通过将此数字作为参数调用该方法。
- 在控制台上显示输出。
广告