简体   繁体   中英

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;
}

  

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM