Why does dividing two int not yield the right value when assigned to double?

Jahoe picture Jahoe · Sep 27, 2011 · Viewed 142.4k times · Source

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?

Answer

Chad La Guardia picture Chad La Guardia · Sep 27, 2011

This is because you are using the integer division version of operator/, which takes 2 ints and returns an int. In order to use the double version, which returns a double, at least one of the ints must be explicitly casted to a double.

c = a/(double)b;