In the line printf("%.1f\n", (double)(7 / 2));
, the order of operations is as follows:
7/2 = 3
(double)3 = 3.0
printf("%.1f\n", 3.0);// Your problem becomes evident.
To achieve the expected behaviour, change (double)(7 / 2)
to 7.0 / 2
(i.e., printf("%.1f\n", 7.0 / 2);
then your code will correctly print 3.5
).
7/2
divides two ints
, thus automatically truncating the result to 3
as is the way with integer division. You then cast the result of the integer division to a double
to produce 3.0
. All these troubles can be avoided if one of the numbers in a mathematical expression is a double
, then the other is implicitly cast to a double
, thus producing a double
in the result.