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

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.

Do not add extra #include lines unless the task says so explicitly.

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

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way