Your problem is that integer arithmetic is performed with integers all the way through, at no point will any operand be changed to a floating point format unless you specifically ask for it.
As such 34 / 40 == 0
because all decimals are stripped, and then trivially 0 * 40 == 0
.
On the other hand 0.85 * 40
features operands of types double
and int
, and as such floating point arithmetic is used and the result is 34.0
(type double
), which is then converted to the int 34
.
Note that a single floating point variable will cause the result to be floating point, so 34.0 / 40 * 40
will also work. BUT beware that this only applies from the point the floating point is introduced in the expression grouping (which then turns into a discussion of operator precedence, see (*) at the bottom).
So (2 / 3) + (4.0 / 5) == 0.8
because (2 / 3) == 0
is evaluated using integer arithmetic, then (4.0 / 5) == 0.8
because one of the operands is floating point, and finally 0 + 0.8 == 0.8
.
If you are in doubt, then apply parenthesis to force the grouping you want. On that note 34 * (40 / 40)
also work - in both integer and floating point.
(*) How expressions are evaluated depends on operator precedence
and manual parenthesis grouping. So for example 34 / 40 * 40
groups as (34 / 40) * 40
because multiplication and division are left-to-right associative and of equal precedence.
On the other hand 2 / 3 + 4.0 / 5
groups as (2 / 3) + (4.0 / 5)
because multiplication and division have higher precedence than addition. This also means that 2 / 3 + 4.0 / 5
and 4.0 / 5 + 2 / 3
both evaluate to the same result, since in both cases the 2/3
group is evaluated using integer arithmetic before the two groups are added.