Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird rounding in C [duplicate]

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);
}
like image 979
illumi Avatar asked Jan 26 '26 20:01

illumi


2 Answers

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:

double sum = ((117+130) / 3.0) + ((130+13) / 3.0);

since we divide by 3.0 rather than 3.

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 .0 to values (.0 will generate a double, while .0f will generate a float - 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 as float after the assignment in this example in any case since v is a float):

float v = 0;
                     /* values shown are BEFORE assignment */
v = (5 / 2);         /* value is 2 due to integer truncation before assignment */
v = (float) (5 / 2); /* 2.0 as integer division occurs 1st, then cast to float */
v = (float) 5 / 2;   /* 2.5 since 5 becomes 5.0 through casting first. */

I borrowed the above example from Division and floating points

like image 108
Levon Avatar answered Jan 28 '26 09:01

Levon


Although you declare sum as float, the right-hand-side of the operation consists of ONLY integers, so it's treated as an integer expression, and divisions are truncated. Try

double sum = ((117 + 130) / 3.0) + ((130 + 13) / 3.0);

instead.