Reputation: 123
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
Upvotes: 0
Views: 1830
Reputation: 108988
29 / 10
performs integer division. Result is 2 (with a remainder of 9).
Try (double)29 / 10
or 29.0 / 10
.
Upvotes: 1
Reputation: 11717
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.
Upvotes: 1
Reputation: 726569
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.
Upvotes: 3