Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get a number within an array that is twice the average

Tags:

c++

I have been assigned to set up an array with points. I am told to get the maximum value, average, and within this same array, if any point in the array is twice the average, I should cout an "outlier." So far I have gotten the average and maximum numbers in the array. but i am unable to set the programme to cout the outlier. Instead it gives me a multiple of the average. here is the programme;

int main()
{
    const int max = 10;
    int ary[max]={4, 32, 9, 7, 14, 12,  13, 17, 19, 18};
    int i,maxv;
    double out,sum=0;
    double av;


    maxv= ary[0];

    for(i=0; i<max; i++)
    {
        if(maxv<ary[i])
            maxv= ary[i];

    }
    cout<<"maximum value: "<<maxv<<endl;

    for(i=0; i<max; i++)
    {

        sum = sum + ary[i];
        av = sum / max;
    }
    cout<<"average: "<<av<<endl;

    out = av * 2;

    if(ary[i]>out)
    {
        cout<<"outlier:  "<<maxv<<endl;
    }
    else
    {
        cout<<"ok"<<endl;
    }


    return 0;
}
like image 490
max Avatar asked May 08 '10 18:05

max


2 Answers

Your code contains a subtle and tricky to spot bug. You're using ary[i] after the final for loop. At this point, the value of i is equal to max, so your if statement is comparing random memory because you're going off the end of the array.

Since this is C++ and not C, you could have avoided this particular bug by declaring your loop variables in the for loop like this

for (int i = 0; i < max; ++i) {
    ....
}
like image 122
Stewart Avatar answered Oct 09 '22 06:10

Stewart


Here is a C++ solution to your assignment, but you probably won't be allowed to hand that in ;-)

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>

int main()
{
    const int N = 10;
    int ary[N] = {4, 32, 9, 7, 14, 12, 13, 17, 19, 18};

    int max = *std::max_element(ary, ary + N);
    std::cout << "maximum: " << max << std::endl;

    double average = std::accumulate(ary, ary + N, 0.0) / N;
    std::cout << "average: " << average << std::endl;

    std::cout << "outlier: ";
    std::remove_copy_if(ary, ary + N,
                        std::ostream_iterator<int>(std::cout, " "),
                        std::bind2nd(std::less_equal<double>(), 2 * average));
    std::cout << std::endl;
}
like image 39
fredoverflow Avatar answered Oct 09 '22 05:10

fredoverflow