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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s