这里,我们需要计算一个数字的各位数字之和。例如,取 123,我们必须找到和为 ' 1 + 2 + 3 = 6 '。
要在 Python 中应用这个程序逻辑,我们需要打开一个 while 循环,直到数字小于零。我们必须使用 mod 运算符从整数中取出数字,并计算和为 sum + digit。然后,我们必须通过将数字 除以 10 从数字中移除一位。最后,在 while 循环的所有迭代之后,我们打印结果。
步骤 1: 使用 input 函数接受用户的输入,并使用 int() 将该字符串转换为整数。
步骤 2: 将 sum 初始化为零。
步骤 3: 打开一个 while 循环,直到数字小于零。
步骤 4: 使用 mod 运算符从数字中取一位。
步骤 5: 计算和为 sum + digit。
步骤 6: 通过将整数除以 10 从整数中移除该数字。
步骤 7: 使用 print 语句打印结果。
要在 Python 中查找数字的各位数字之和,我们需要了解以下概念,请参考这些概念以获得更好的理解。
n=int(input("Enter a number:"))
sum=0
while(n>0):
dig=n
sum=sum+dig
n=n//10
print("The sum of digits in the number is:",sum)
Enter a number : 123 The sum of digits in the number is: 6