The problem is not with the format specifier, rather with the arithmatic operation.
By saying
k = (i+j)/2;
where, i
and j
and 2
- all are int
s, you're doing integer division, and then, storing the result in a double
. For integer division,
[..] When integers are divided, the result of the /
operator is the algebraic quotient with any fractional part discarded [...]
which is commonly known as "truncation towards zero". To avoid that from happenning, you need to enforce floating point arithmetic, by forcing or casting one of the operands to double
(or float
). Something like
k = ((double)i+j)/2;
or,
k = (i+j)/2.0; //2.0 is of type double
The point here is, if, in the operation, one of the operands is of the higher rank (double
or float
is higher ranked that int
), all the operands will first be converted to the higher rank, and then the operation will be performed and the result will be of the type of the higher ranked type.