dev/c/avg_task/avg_arr.c

55 lines
760 B
C

#include <stdio.h>
#include <stdlib.h>
int avg(size_t N, int *a)
{
size_t i;
int mean = 0,
rem = 0;
for (i = 0; i < N; i++) {
int tmp = a[i] - mean;
int ii = (int)i;
mean += tmp / (ii + 1);
rem += tmp % (ii + 1);
if (abs(rem) > ii) {
if (rem > 0) {
rem -= ii + 1;
mean++;
}
else {
rem += ii + 1;
mean--;
}
}
}
// округление до ближайшего целого
//~ if (abs(rem) > ii / 2)
//~ if (rem > 0)
//~ mean++;
//~ else
//~ mean--;
return mean;
}
int main(int argc, char *argv[])
{
const size_t N = 88;
int *a = (int *)malloc(N * sizeof(int));
size_t i;
for (i = 0; i < N; i++)
a[i] = rand() % 1024;
printf("avg(a[]) = %d\n", avg(N, a));
free(a);
return 0;
}