Why does multiplication with and without parentheses make a big difference?

Viewed 80

If I multiply without parentheses to get a Fahrenheit number I get a different number than if I multiply with them. Why is that?

#include <stdio.h>

int main (){
    double userinput, fahr1, fahr2;

    printf("Enter a number in Cels ");
    scanf("%lf", &userinput);

    fahr1 = userinput*(9/5)+32;
    fahr2 = userinput*9/5+32;

    printf("fahr1 = %f and fahr2 = %f \n", fahr1, fahr2);

    return 0;
}

Outputs:

Enter a number in Cels 15
fahr1 = 47.000000 and fahr2 = 59.000000 
3 Answers

(9/5) is integer division, and evaluates to 1. But userinput*9 is evaluated as a double, and then division by 5 is treated as a double as well.

The explanation is very easy

Without the brackets: 15.0*9=135.00 135.0/5 = 27.00 27.0+32 = 59.00

With brackets: 9/5 = 1 (integer division) 15.0 * 1 = 15.0, 15.0 + 32 = 47.00

Here

1) userinput*(9/5)+32;

    15.0*(1)+32   //1.8 goes to 1 because integer division
    15.0+32
    47.0

2) userinput*9/5+32;

    15.0*9/5+32
    135.0/5+32
    27.0+32
    59.0  
Related