2

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
millsware
  • 23
  • 3

2 Answers2

4

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
3

Chances are good that both L and W is declared as int. Then in the first case, (L/W) will also be treated as an int, and therefore is floored, which causes the error.

Side note: even if they are declared float or double, floating point arithmetics means multiplication and division is not associative.

user12986714
  • 741
  • 2
  • 8
  • 19