在這個簡單的 python 程序中,我們必須找到一個數字的十進位位總和。這是一個初級 python 程序。
要理解這個例子,您應該了解以下 Python 編程主題:
- Python 語法
- Python 循環
- Python 運算符
如何求一個數的位數之和?
在這個關於數字的基本 python 程序中,我們需要計算一個數字的十進位位總和,這意味著,取一個數字 123,我們必須找到總和為『1+2+3 = 6』
要在這個簡單的 python 程序中應用這個邏輯,我們需要打開一個while loop
直到數字小於零。我們必須使用 mod 運算符從數字中提取數字,並在 python 中計算總和為總和+數字。然後,我們必須通過將數字除以 10 來刪除數字中的一個數字。最後,我們用 python 語言列印 while 循環所有迭代後的結果。
演算法
步驟 1: 使用輸入函數接受用戶的輸入,並使用 Python 編程語言中的int()
將該字元串轉換為整數。
步驟 2: 將和初始化為零。
第三步:打開一個while loop
直到數字小於零。
步驟 4: 使用模塊運算符從數字中提取一個數字。
第五步:計算總和為總和+數字。
第 6 步:將數字除以 10,去掉數字。
步驟 7: 使用列印語句列印結果。
Python 源代碼
n=int(input("Enter a number:"))
sum=0
while(n>0):
dig=n%10
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
原創文章,作者:E2WQE,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/129597.html