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?
Best Answer
This is because you are using the integer division version of
operator/
, which takes 2int
s and returns anint
. In order to use thedouble
version, which returns adouble
, at least one of theint
s must be explicitly casted to adouble
.