繁体   English   中英

如何计算整数的各个数字之和并在最后打印原始整数?

[英]How do I calculate the sum of the individual digits of an integer and also print the original integer at the end?

我希望在 Python 中创建一个函数来计算作为参数传递给它的给定数字的各个数字的总和。

我的代码如下:

number = int(input("Enter a number: "))
sum = 0

while(number > 0):
    remainder = number % 10
    sum = sum + remainder
    number = number //10

print("The sum of the digits of the number ",number," is: ", sum)

这段代码一直工作到我需要打印原始数字+语句+总和的最后一个打印命令。 问题是原来的数字每次都变成0(总和是对的)。

我如何计算这个但同时在打印命令中显示原始数字?

保留另一个变量来存储原始数字。

number = int(input("Enter a number: "))
original = number
# rest of the code here

另一种解决方法:

您不必将数字解析为int ,将其视为从input()函数返回的str 然后迭代每个字符(数字)并添加它们。

number = input("Enter a number: ")
total = sum(int(d) for d in number)
print(total)
number = input("Enter a number: ")
total = sum((int(x) for x in list(number)))
print("The sum of the digits of the number ", number," is: ", total)

正如其他人指出的那样,甚至不需要转换为int因为我们一次只操作一个字符。

您无需转换为 int 就可以完全做到这一点:

ORD0 = ord('0')
number = input("Enter a number: ")
nsum = sum(ord(ch) - ORD0 for ch in number)

它会计算垃圾,如果有人输入不是数字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM