ninjastyleninja
ninjastyleninja

Reputation: 3

Finding the element closest to average - c

How can I find the element closest to average in c array. This passes most tests however when I type in the sequence 4-1-5-7-2 it prints out 2, instead of 5.

#include <stdio.h>
#include <math.h>
int main() {
    int A[50], n, k = 0, i = 0;
    double avg = 0;
    scanf_s("%d", &n);
    do {
        scanf_s("%d", &A[i]);
        avg += (double)A[i] / n;
    } while (++i < n);
    printf("\n%f\n", avg);
    for (i = 1; i < n; i++) {
        if (fabs(A[k] - avg) > fabs(A[i]) - avg) {
            k = i;
        }
    }
    printf("%d", A[k]);
    return 0;
}

  

Upvotes: 0

Views: 92

Answers (1)

Rumaisa Habib
Rumaisa Habib

Reputation: 71

In your if statement, replace fabs(A[i]) - avg with fabs(A[i] - avg) to get the absolute difference.

Upvotes: 2

Related Questions