Skip to content
Exercise · Casts and Aliases · lesson 6 of 6

Exercise: average without overflow

Write a function int average(int a, int b) that returns the arithmetic mean of the two numbers. Drop the fraction, as / does with two int operands: 7.5 becomes 7, and -7.5 becomes -7.

  • average(10, 20) → 15
  • average(-7, -8) → -7
  • average(INT_MAX, INT_MAX) → INT_MAX

Constraints: a and b are any int values from INT_MIN to INT_MAX, so a + b may not fit in an int.

average.cpp — cpp
cpp · 4 lines
Ctrl+Enter run · Esc leave editor