Why does dividing two int not yield the right value when assigned to double?
How come that in the following snippet
int a = 7;
int b = 3;
double c = 0;
c = a / b;
c
ends up having the value 2, rather than 2.3333, as one would expect. If a
and b
are doubles, the answer does turn to 2.333. But surely because c
already is a double it should have worked with integers?
So how come int/int=double
doesn't work?
Solution 1:
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;
Solution 2:
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.
Solution 3:
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
.