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;
}
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) {
....
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With