Search code examples
ccs50parenthesesarithmetic-expressionsinteger-division

Why do these parentheses give different answers in C?


I was working on readability for CS50 PS 2, and was getting incorrect outputs on the grade level.

Debugging showed that the input values were correct, but the output was wrong. Hand calculating using the inputs gave the correct answer.

I simplified the first part of the equation and found this:

Using the values of 214 for L and 56 for W, the expression:

float R = (0.0588 * (L / W) * 100);

outputs 17.64, which is wrong.

When I use:

float R = (0.0588 * L / W * 100);

it outputs 22.47, which is correct.

I can't figure out why.


Solution

  • The expression

    float R = (0.0588 * (L / W) * 100);
    

    will develop to

    float R = 0,0588 * 3 * 100;
    

    which is 17.64, when rounded to two decimal places.

    The result of L / W integer division is an int, so the result 3.8... will be truncated to 3.

    To correct this, at least one of the variables W or L must be of type float or double.

    The expression

    float R = (0.0588 * L / W * 100);
    

    will develop to

    float R = ((0,0588 * 214) / 24) * 100 //parenthesis to illustrate the sequence 
    

    which outputs the correct result, 22.47, when rounded to two decimal places.