c++variablesdoubleinteger-division

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

  • 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;