Why does dividing two int not yield the right value when assigned to double?
Here it is:
a) Dividing two int
s performs integer division always. So the result of a/b
in your case can only be an int
.
If you want to keep a
and b
as int
s, yet divide them fully, you must cast at least one of them to double: (double)a/b
or a/(double)b
or (double)a/(double)b
.
b) c
is a double
, so it can accept an int
value on assignement: the int
is automatically converted to double
and assigned to c
.
c) Remember that on assignement, the expression to the right of =
is computed first (according to rule (a) above, and without regard of the variable to the left of =
) and then assigned to the variable to the left of =
(according to (b) above). I believe this completes the picture.
This is because you are using the integer division version of operator/
, which takes 2 int
s and returns an int
. In order to use the double
version, which returns a double
, at least one of the int
s must be explicitly casted to a double
.
c = a/(double)b;
With very few exceptions (I can only think of one), C++ determines the
entire meaning of an expression (or sub-expression) from the expression
itself. What you do with the results of the expression doesn't matter.
In your case, in the expression a / b
, there's not a double
in
sight; everything is int
. So the compiler uses integer division.
Only once it has the result does it consider what to do with it, and
convert it to double
.