0

I am trying to execute the following code

var n = 100;
var sum =0;
while(n>0)
{
sum = sum + n%10;
n = n/10;
}
console.log(sum);

The result should be 1 but javascript is returning

1.1111111111111112

Also, when I ran individual statements it is giving perfectly fine result, what could be the possible reason?

Pranjal Diwedi
  • 1,012
  • 1
  • 7
  • 8
  • 2
    first iteration n = 100, second n = 10, 3rd n = 1, 4th n= 0.1, 5th n=0.01, until n is small enough to be equal to 0, at 1e-324 on my machine – Kaiido Nov 14 '16 at 07:20
  • 1
    *The result should be 1*: Why? – Hanky Panky Nov 14 '16 at 07:20
  • 4
    Why would you think that it should be 1? When `n` goes into decimal numbers `0.1%10 == 0.1`, `0.01%10 == 0.01` you get `n` back so as you add them to the previous sum you get `1.1111.....` Also you are lucky that at certain precision the value just becomes 0 as otherwise you would have an infinite loop – Patrick Evans Nov 14 '16 at 07:20
  • `n%10` for numbers less than `10` is `n`. The numbers don't have to be integers for it to work (maybe they should? who knows) – apokryfos Nov 14 '16 at 07:22
  • 1
    `n/10` will return a floating value. Use `n=parseInt(n/10)` – Rajesh Nov 14 '16 at 07:22

2 Answers2

7

The result it is giving is correct -

Lets go into while loop

For first iteration n=100 so n%10 = 0 and sum = 0, after first loop sum = 0 and n = 10

In second iteration n%10 = 0 and sum = 0, after second iteration sum = 0 and n = 1

For third iteration n%10 = 1 and sum =0, after third iteration sum = 1 and n = 0.1

For fourth iteration n%10 = 0.1 and sum = 1, after fourth iteration sum = 1.1 and n = 0.01

and so on so forth

finally the answer would be 1.1111111111....... tending to infinity so it becomes 1.1111111111111112

Hope this helps

EDIT

If you want final answer as 1, intialise n as 0.9(n = 0.9)

madhur
  • 973
  • 1
  • 14
  • 23
  • Finally! someone has come up to present the fact that OP's expectation is incorrect, instead of just rounding a number down to a completely invalid value. Way to go! – Hanky Panky Nov 14 '16 at 07:33
  • while this anwer declares what happen, the op does not get what is requested, a result with one. – Nina Scholz Nov 14 '16 at 07:40
  • @NinaScholz Edited, getting final answer as 1 is just playing with numbers here and there – madhur Nov 14 '16 at 07:48
2

No, the result won't be 1. Notice that your loop is dividing n by 10 every iteration, and that the continuing condition is n > 0, which will take many iterations till it happens:

  • n=100, n%10=0
  • n=10, n%10=0
  • n=1, n%10=1
  • n=0.1, n%10=0.1
  • n=0.01, n%10=0.01
  • ...

So, the result is correct: 1.1111111... The 2 at the end is no more than a rounding decimal error (minimal).

Little Santi
  • 8,563
  • 2
  • 18
  • 46