Why is the following:
int main(void)
{
double b = 11/2;
double a = 2;
printf("%lf\n", a + b);
printf("%lf\n", b);
}
printing, respectively, 7.000000 and 5.000000
I tried printing just the value of 5.5, without having it in a variable and then passing it to printf and it worked, but why does this code don't?
The constants 11
and 2
have type int
, so dividing them performs integer division which truncates any fractional part.
Use floating point constants instead so floating point division happens.
double b = 11.0/2.0;