The problem is integer truncation .. you are dividing two integers => the result will be another integer with the fractional part thrown away. (So for instance in the case when the real result of an integer division would be 3.9, truncation would make it 3 (ie. it doesn't round)).
In your case, if you change this to:
x2 = 360 / 4095.0; /* one of the operands now has a decimal point */
you'll get
0.087912, 0.087912
as output.
I.e., as soon as one or both of the operands of the division operator /
are float/doubles, the result will be too (i.e., it will be "promoted" to float/double). So I could have changed x2
to
x2 = 360.0 / 4095.0;
or
x2 = 360.0 / 4095;
and would have gotten the same result as above.
As mentioned by @chris just using a .
is sufficient too.
Re your question above about precision:
You are already working with long doubles .. I don't think internally you can change anything unless you use some special library, but you can certainly display more digits. E.g.,
printf("%Lf, %.20Lf \n",x1, x2);
will yield
0.087912, 0.08791208791208791895
Finally, as @edA-qa mort-ora-y reminds us, you can also cast values to certain types, but it matters when you do it. A simple example (note that the values end up as float
after the assignment 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. */