This time, a direct answer:
...why does this work,
double QD1=0;
QD1=24+c; QD1=QD1/513;
QD1
is clearly a double
. To Java, 24 is an integer constant. If c
is an integer type, c
is added to 24 using integer arithmetic and the result is converted to double
and then assigned to QD1
. If c
is a floating point type, 24 is promoted to double
, added to c
and the double
result is assigned to QD1
. Either way, the division of QD1
is a double divided by an integer constant. The integer constant is promoted to double and floating point division is performed with a double result assigned to QD1
.
but this doesn't.
double QD1=0;
QD1=(24+c)/513;
In this case, if c
is an integer type, the entire expression on the right-hand side operates on integers and returns an integer type. In Java, integer division truncates any fractional part which might result if the division were instead performed using floating point values and operators. Once evaluation of the right-hand side has completed, the integer result is promoted to double
before assigning it to QD1
, but by then, the fractional part of the intended result has already been lost.
The way to prevent this particular problem in practice is to always provide a fractional part to all integer constants used in floating point calculations. E.g. Change the code in both examples to use 24.0
and 513.0
for the constants. Always do this even in code which works as expected. Future edits may "break" the implementation when integer types are not intended.