Calculation of sum of digits

Asked

Viewed 2,170 times

1

Write a program that receives an integer number in the input, calculate and print the sum of the digits of this number in the output

Example:

>>>Digite um número inteiro: 123

>>>6

Tip: To separate the digits, remember: the operator "//" makes an entire division by throwing away the rest, that is, that which is less than the divisor; The operator "%" returns only the rest of the entire division by throwing away the result, that is, all that is greater than or equal to the divisor.

I made the code, however, it has a repeat bug that I can’t fix. Can someone help me?

x=int(input("Digite um número para que seus digitos sejam somados: "))

soma=0
while (x>0):
    resto = (x // 10)%10
    resto_cont=(x%10)
    resto_cont2=(x//100)
    soma = resto + resto_cont + resto_cont2
print("valor é", soma)

1 answer

0


Your program gets stuck inside the while and never comes out because the value of x never changes.

Besides, if you have one while running through the digits, you should have soma = soma + alguma_outra_coisa.

It should also be noted that in while, You should be separating the last digit from the others. You’re actually separating the last one, but when it comes to separating the others, you’re doing it wrong and forgetting that you’re inside the while.

Do so:

x = int(input("Digite um número para que seus dígitos sejam somados: "))

soma = 0
while x > 0:
    resto = x % 10
    x = x // 10
    soma = soma + resto

print("O valor é", soma)

With that input:

123

That’s the way out:

O valor é 6

See here working on ideone.

  • 1

    Ah, thank you so much for your help!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.