Simvik

Divide and round to nearest

Integer division that rounds to the nearest value instead of truncating. A medium embedded C problem (Integers and data types), run and graded in the browser.

medium · Integers and data types · division · rounding

Integer division in C truncates, so 7 / 2 is 3. Return n / d rounded to the nearest integer, with halves rounded up: 7 / 2 gives 4 and 9 / 4 gives 2.

d is never 0. The function must be correct for every n, including values close to UINT32_MAX.

Starter code

uint32_t div_round(uint32_t n, uint32_t d) {
  // Return n / d rounded to the nearest integer (halves round up).
  return n / d;
}

Example tests

Half rounds up

printf("%u %u\n", div_round(7, 2), div_round(10, 4));

Expected output:

4 3

Below half rounds down

printf("%u %u\n", div_round(9, 4), div_round(1, 3));

Expected output:

2 0

Learn it first

More Integers and data types problems