OP: "temp: 0, r: 1.000000 which says temp1 = 0 which is typecasting of 1.000000 by long."
A: Conversion of double
to long
is working, for double
is less than 1.0.
Code is printing a rounded value of the double
, not its exact value, which is slightly less than 1.0. (long) some_number_slightly_less_than_1
is 0
. Try printing the double
with more precision "%.20le"
instead of "%lf"
.
Given typical IEEE binary64 floating point, when code starts with a double
of 1010.001100
, code is really starting with a 1010.00109999999995125108....
.
As to why the wrong answer of 10.617188
, I suspect unposted code binary_decimal();
Code has error:
// floatFract = floatFract + (double) temp1 / (double) i;
floatFract = floatFract + (double) temp1 / (double) k;
...
// wrong result of 10.61718750000000000000
// correct result follows
10.00109989999999982047....
// or to 6 decimal places
10.001100
Minor: note that the below code only works for a double f
in the range LONG_MIN
to LONG_MAX
.
integral = (long)f;