Search code examples
javaccastingexpressionprimitive

C vs Java primitive casting and expressions


Why does this equation produce two different values for e in C (32-bit) and Java (64-bit)? They are off by an unexpectedly large amount.

int a, b, c, d;
double e;

a = -12806;
b = 1;
c = 800;
d = 19209;

double f = (32768 / 10.24);

e = (a + (double) b / c * d) / f;

C produces -3.9940624237060547. Java produces -3.9943714843750002.

UPDATE:

Sorry folks, this error appears to be something else than I expected. I reduced my code to just this equation and the numbers it produces are much closer.


Solution

  • In Java the implicit braces are a bit different:

        int a, b, c, d;
        double e;
    
        a = 3;
        b = 4;
        c = 5;
        d = 6;
        e = a + (double) b / c * d;
        System.out.println("e=" + e);
        e = a + (((double) b) / c) * d; // Java: 7.8
        System.out.println("e=" + e);
    

    If you run this in C you will see the difference.