- slide 1 of 3
Assignment between double and float
As expected, you can store a float value in a float variable and a double value in a double variable. Since float is smaller than double, C allows you to store a float value in a double variable without any problems. However, if you assign a double to a float, some precision may be lost. Consider the following:
double d = 987.654321;
float x = d;
printf("%f \n", x);
Since a float variable allows at most 7 digits of precision, we should expect that the value of d may not be assigned precisely to x. Indeed, when run using one compiler, the value 987.654297 was printed for x. When d was changed to 987654321.12345, the value printed was 987654336.000000. In both cases, about 6 or 7 digits of precision were retained.
As an exercise, see what values would be printed using your compiler.
- slide 2 of 3
Expressions with integer and floating-point values
It is quite common to use expressions involving both integer and floating-point values, for example,
a / 3 where a is float
n * 0.25 where n is int
In C, the rule for such expressions is:
If either operand of an arithmetic operator is floating-point, the calculation is done in floating-point arithmetic. The calculation is done in double unless both operands are float, in which case the calculation is done in float.
In the first example above, the integer 3 is converted to float and the calculation is done in float. In the second example, n is converted to double (since 0.25 is double) and the calculation is done in double.
How do we get the exact value of an integer division, 19/5, say? We can force a double precision calculation by writing one or both constants as double, thus: 19/5.0, 19.0/5 or 19.0/5.0. We can also use a cast, as in
(double) 19 / 5
A cast allows us to force the conversion of one type to another. Here, the int 19 is cast to double, forcing 5 to be converted to double and a double precision division is performed.
However, we must be careful with a construct like
(double) (19 / 5)
since it may not do what we think. This does NOT do a floating-point division. Since both constants are integer, the expression inside the brackets is evaluated as an integer division (which discards the remainder), giving 3; this value is converted to double, giving 3.0.