简体   繁体   English

找到最接近平均值的元素 - c

[英]Finding the element closest to average - c

How can I find the element closest to average in c array.如何在 c 数组中找到最接近平均值的元素。 This passes most tests however when I type in the sequence 4-1-5-7-2 it prints out 2, instead of 5.这通过了大多数测试,但是当我输入序列 4-1-5-7-2 时,它会打印出 2,而不是 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.在您的 if 语句中,将fabs(A[i]) - avg替换为fabs(A[i] - avg)以获得绝对差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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