Operator precedence
Fix an expression that is evaluated in the wrong order. An easy embedded C problem (Variables and operators), run and graded in the browser.
easy · Variables and operators · precedence · debugging
This function should return the average of a and b, with the fraction dropped. It returns something else. Find the bug and fix it.
Starter code
int average2(int a, int b) {
return a + b / 2;
}Example tests
Ten and twenty
printf("%d\n", average2(10, 20));Expected output:
15Four and six
printf("%d\n", average2(4, 6));Expected output:
5Learn it first
- Variables and operators · Storing values, doing arithmetic, comparing, and the two surprises of integer maths.
More Variables and operators problems
- Average of three · Add three values and divide.
- Last digit · Use the remainder operator.
- Celsius to Fahrenheit · Fix a formula that divides too early.
- Time in seconds · Combine several values into one total.
- Even or odd · Produce a yes-or-no answer as 1 or 0.
- Percentage · Keep precision by ordering the operations correctly.
- Does it fit in a byte? · Combine two comparisons with a logical operator.