Possible Duplicate:
C programming division
in the following code example the result should yield 130.0 yet once compiled, I get 129.0. Is the right hand side not producing enough precision to get an accurate result? Is there a way around this?
#include<stdio.h>
int main(void) {
double sum = ((117+130)/3) + ((130+13)/3);
printf("sum: %f\n", sum);
}
What you are observing is the result of integer truncation. When doing integer division with two integer operands, the result will be another integer, with the fractional part thrown away. Note that this is different from rounding, e.g, with truncation 3.8 will become 3.
This will give you your expected output:
since we divide by
3.0rather than3.I.e., if at least one, or both of the operands in an integer division is a float type, the result will be a float. (Note that I’m using float/double here somewhat interchangeably with regard to
ints and truncations)In addition to appending a
.or.0to values (.0will generate adouble, while.0fwill generate afloat– as pointed out by @Morwenn’s helpful comment below), we can also explicitly cast ints to floats, but it matters when we do it. A simple example (note that the values end up asfloatafter the assignment in this example in any case sincevis afloat):I borrowed the above example from Division and floating points