namarino namarino - 1 year ago 63
C Question

C double not working as expect

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download