我必須計算數字的位數之和。它適用于正數,但不適用于負數。我應該在這里添加什么?
n = int(input("Input a number: "))
suma = 0
while(n > 0):
if n > 0:
last = n % 10
suma = last
n = n // 10
print("The sum of digits of the number is: ", suma)
輸入輸出
Input a number: -56
The sum of digits of the number is: 0
uj5u.com熱心網友回復:
簡單的解決方法是這樣做,n = abs(n)然后它將與您的代碼一起使用。
如果你真的*lazy*可以簡化這個方法:
n = abs(n)
sum_digit = sum(int(x) for x in str(n)) # are we cheating? ;-)
uj5u.com熱心網友回復:
當您傳遞一個負數時,第一個 while 回圈的條件while(n > 0):將為 false,因此將永遠不會執行以下代碼,并且 sum 的值將永遠不會更新并保持為 0。
使用abs()函式獲取絕對值。
n = abs(int(input("Input a number: ")))
suma = 0
while n > 0:
if n > 0:
last = n % 10
suma = last
n = n // 10
print("The sum of digits of the number is: ", suma)
uj5u.com熱心網友回復:
也許你可以利用absand divmod:
def get_int_input(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print("Error: Enter an integer, try again...")
def get_sum_of_digits(num: int) -> int:
num = abs(num)
total = 0
while num:
num, digit = divmod(num, 10)
total = digit
return total
def main() -> None:
n = get_int_input("Input an integer number: ")
sum_of_digits = get_sum_of_digits(n)
print(f"The sum of digits of the number is: {sum_of_digits}")
if __name__ == "__main__":
main()
示例用法 1:
Input an integer number: 123456789
The sum of digits of the number is: 45
示例用法 2:
Input an integer number: -56
The sum of digits of the number is: 11
示例用法 3:
Input an integer number: asdf
Error: Enter an integer, try again...
Input an integer number: 2.3
Error: Enter an integer, try again...
Input an integer number: -194573840
The sum of digits of the number is: 41
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/489293.html
標籤:Python python-3.x
