简体   繁体   English

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

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

I wish to create a Function in Python to calculate the sum of the individual digits of a given number passed to it as a parameter.我希望在 Python 中创建一个函数来计算作为参数传递给它的给定数字的各个数字的总和。

My code is as follows:我的代码如下:

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)

This code works up until the last print command where I need to print the original number + the statement + the sum.这段代码一直工作到我需要打印原始数字+语句+总和的最后一个打印命令。 The problem is that the original number changes to 0 every time (the sum is correct).问题是原来的数字每次都变成0(总和是对的)。

How do I calculate this but also show the original number in the print command?我如何计算这个但同时在打印命令中显示原始数字?

Keep another variable to store the original number.保留另一个变量来存储原始数字。

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

Another approach to solve it:另一种解决方法:

You don't have to parse the number into int , treat it as a str as returned from input() function.您不必将数字解析为int ,将其视为从input()函数返回的str Then iterate each character (digit) and add them.然后迭代每个字符(数字)并添加它们。

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)

As someone else pointed out, the conversion to int isn't even required since we only operate a character at a time.正如其他人指出的那样,甚至不需要转换为int因为我们一次只操作一个字符。

You can do it completely without a conversion to int:您无需转换为 int 就可以完全做到这一点:

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

It will compute garbage, it someone enters not a number它会计算垃圾,如果有人输入不是数字

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

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