[英]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.