我需要找到与给定数字中的平均值最接近的(和次要的)数字。

时间:2017-12-02 21:30:58

标签: c++ arrays

我需要找到与给定数字中的平均值最接近的(和次要的)数字。例如:

如果给定的数字是1,2,3,4,5,则平均值为3,最接近的数字为2和4,但是次要数字为2,因此结果应为2。

或者,如果给定的数字是1,325,350,299,则平均值为243.75,因此最接近的数字为299。

我只能找到平均值。

#include <iostream>
using namespace std;
int main() {
    int n, i;
    float num[100], sum=0.0, average;
    n = 10;
    while (n > 100 || n <= 0) {
           cin >> n;}
    for(i = 0; i < n; ++i) {
        cin >> num[i];
        sum += num[i];
        } average = sum / n;
    cout << average;
    return 0;
    }

3 个答案:

答案 0 :(得分:0)

找到平均值后,您可以再次迭代数组并找到最接近的数字:

float closest = num[0];
float diff = abs(average - closest);
for(i = 1; i < n; ++i) {
    float curr_diff = abs(average - num[i]);
    if (curr_diff < diff || (curr_diff == diff && num[i] < closest) {
        closest = num[i];
        diff = curr_diff;
    }
}

答案 1 :(得分:0)

以下是使用算法函数的解决方案:(std::upper_boundstd::sort)和<numeric>库中的函数std::accumulate

#include <algorithm>
#include <numeric>
#include <iostream>
#include <cmath>

int main()
{
    float values[] = { 1, 2, 3, 4, 5 };
    const int numValues = sizeof(values) / sizeof(float);

    // get the average
    float average = std::accumulate(values, values + numValues, 0.0F) / numValues;

    // sort the values
    std::sort(values, values + numValues);

    // find where the average would be inserted
    float *closest = std::upper_bound(values, values + numValues, average);

    // assume closest is the value greater than average
    float *absClosest = closest;

    // check number before the insertion point
    if (closest != values)
    {
        float *closest2 = closest - 1;

        // get the difference in both numbers and average
        if (fabs(*closest2 - average) < fabs(*closest - average))
            absClosest = closest2;
    }
    std::cout << "The average is " << average << "\nThe closest to average is " << *absClosest;
}

Live Example

答案 2 :(得分:0)

您必须检查最近的值,较小的值并且不等于平均值​​。因此可能是这样的:

#include <cstdio>
#include <math.h>

using namespace std;

int main( int argc, char ** argv )
{
int n = 5;
float num[] = {1,2,3,4,5};
float average = 3;
float smallValue = 0.0001;

float closest = num[0];
float diff = fabs(average-closest);

for (int i = 1; i < n; ++i) {
    float curr_diff = fabs(average - num[i]) ;
    if ((curr_diff + smallValue) < diff && fabs(num[i] - average) > smallValue)
    {
        closest = num[i];
        diff = curr_diff;
    }
}
return 0;