namarino - 4 months ago 26

C Question

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

Answer

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.