计算数字的位数和时出现负数错误

  • 本文关键字:错误 数字 计算 python python-3.x
  • 更新时间 :
  • 英文 :


我要计算这个数字的数字之和。它适用于正数,但不适用于负数。我应该在这里加上什么?

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

简单的修复方法是执行n = abs(n),然后它将与您的代码一起工作。

如果你真的是*lazy*你可以简化这个方法:

n = abs(n)
sum_digit =  sum(int(x) for x in str(n))  # are we cheating?  ;-)

当您传递一个负数时,第一个while循环的条件while(n > 0):将为假,因此以下代码将永远不会执行,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)

也许你可以利用absdivmod:

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

最新更新