-1

I wrote this function sum_of_digits which takes n (a number) and returns the sum of its digits

def sum_of_digits(n):
    sum = 0
    while n > 0:
        d = n%10
        sum+=d
        n/= 10
    return sum

print(sum_of_digits(9))

I have no clue what is going wrong, but the last statement print(sum_of_digits(9)) returns 10.000000000000004, and I cant figure how to correct it. Can anyone help me?

I have already tried rephrasing the same code in many different ways, I've tried using a for loop, and nothing I seem to do helps the code.

1 Answers1

0

Instead of division operator / try using floor division // to avoid this floating points errors.
Also, you may refer this post to understand this concept clearly.
Is floating point math broken?

Python learner
  • 1,159
  • 1
  • 8
  • 20