How to get a number closest to the average in c++?
Posted
by
Alex Zielinski
on Stack Overflow
See other posts from Stack Overflow
or by Alex Zielinski
Published on 2013-10-26T14:55:04Z
Indexed on
2013/10/26
15:54 UTC
Read the original article
Hit count: 330
What I'm trying to achieve is to take the average of the numbers stored in the array and find the number which is closest to it. My code compiles, but has an error just after starting. I think it's something to do with the memory handling (I don't feel confident with pointers, etc. yet) Could some nice guy take a look at my code and tell me what's wrong with it? (don't be hard on me, I'm a beginner)
#include <iostream>
#include <cmath>
using namespace std;
double* aver(double* arr, size_t size, double& average);
int main()
{
double arr[] = {1,2,3,4,5,7};
size_t size = sizeof(arr)/sizeof(arr[0]);
double average = 0;
double* p = aver(arr,size,average);
cout << *p << " " << average << endl;
}
double* aver(double* arr, size_t size, double& average){
int i,j,sum;
double* m = 0;
int tmp[7];
for(i=0;i<size;i++)
sum += arr[i];
average = sum/size;
for(j=0;j<size;j++){
tmp[j] = arr[j] - average;
if(abs(tmp[j])>*m)
*m = tmp[j];
}
return m;
}
© Stack Overflow or respective owner