0

I am writing some where I need to divide 29 by 10. But when I do so and store it in a double, it outputs 2.0000 instead of 2.9. Can someone explain why this is happening and how to fix it?

double a = 29/10;

output: 2.0000
namarino41
  • 123
  • 1
  • 15
  • 1
    Possible duplicate of [Why dividing two integers doesn't get a float?](http://stackoverflow.com/questions/16221776/why-dividing-two-integers-doesnt-get-a-float) – OldProgrammer Nov 05 '16 at 21:56

3 Answers3

3

The double works as expected, it's just that you are not assigning it an expression of type double.

What you assign it is an int, a result of dividing 29, an int, by 10, an int. This is 2, because the remainder is discarded when you divide integers.

Changing 29 to 29.0 or 10 to 10.0 will fix this problem.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

29 / 10 performs integer division. Result is 2 (with a remainder of 9).

Try (double)29 / 10 or 29.0 / 10.

pmg
  • 106,608
  • 13
  • 126
  • 198
1

This is a classical C mistake: you are doing an integer division and requesting a floating point result.

You should do a floating point division with

double a = 29.0/10.0;

You should read What Every Computer Scientist Should Know About Floating-Point Arithmetic if you want to discover all details about floating point operations.

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49