Problem
Sometimes an implicit conversion from a floating type to an integer type produces unexpected results. For example, the following two methods produce different answers:
double0 = -71.1;long2 = (double0 * 1000000); /* This will appear as -71099999 */
double1 = (double0 * 1000000); long2 = double1; /* This will appear as -71100000 */
The following test case illustrates this issue:
/******************************/
/* Compile with " cc test.c " */int main()
{
double double_org=-71.1, double_temp=0;
long long_cast=0, long_implicit=0, long_explicit=0;printf("\nOriginal value for double: %f\n\n", double_org);/* Do the basic math for comparison */ double_temp = (double_org * 1000000); printf("Double to double: %f\n", double_temp);
/* Cast this to a long */ long_cast = (long) double_temp; printf("Double to long, cast: %ld\n", long_cast);
/* Explicit conversion */ long_explicit = double_temp; printf("Double to long, explicit conversion: %ld\n", long_explicit);
/* Math and conversion in one step (implicit conversion) * This gives a different result */
long_implicit = (double_org * 1000000); printf("Double to long, implicit conversion: %ld\n\n", long_implicit);
/* Check the two values against each other to make sure the * difference is real and not a figment of printf */
if (long_implicit == long_explicit) printf("Real values are equal.\n"); else printf("Real values are different!\n\n");
exit(0);}/******************************/ Cause
It would appear that an explicit cast produces a different result than an implicit conversion. However, the following shows that cast is irrelevant. The example below saves the result of the multiplication in a long double. After:
long_double1 = (double_org * 1000000)the assignments:long_implicit = long_double1and:long_cast = (long)long_double1produce identical results.To understand the real reason for the difference it is necessary
to examine how the multiplication is carried out. Our compiler
does the multiplication in extended double precision in the
floating register stack. This behavior is explicitly permitted
by the C standard. This means that the actual operation looks
more accurately like this:(long double)double0 * 1000000.0LThe incoming value for double0 is (more accurately):
-71.0999999999999943and the result of the multiply is:
-71099999.9999999943When this is rounded back to double for the assignment to double1,
it becomes - -71100000.000000000. When this is assigned to long2,
the result is the expected -71100000. On the other hand, if the
result of the multiply is directly assigned to long2, the result of
truncating -71099999.9999999943 is naturally -71099999. Solution
Use the implicit conversion method for more accurate results:
long2 = (double0 * 1000000);