Monthly Archives: January 2018

Average of an Array

I went looking for this but couldn’t seem to find it. Bad search terms, maybe? Anyway, have at it:

#include <math.h> /* 'div()' rounds toward zero */
int average(int n, const int * a)
{
  int val = 0;
  int rem = 0;
  for (int i = 0; i < n; ++i) {
    div_t d = div(a[i], n);
    val += d.quot;
    rem += d.rem;
  }
  return val + div(rem, n).quot;
}

Works for positive and negative values. There’s a minimal chance of overflow here (rem is at most (n-1)*n). Can anybody do any better?

Advertisements