Finding the average of an array

I am having trouble using a pointer in my average function trying to find the average value of the array.

Here is my code.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

double average(double* a, int a_size)
{
	int array[10];
	int *traverse = array;
	for(int i = 0; i < 10; i++)
	{
		*(traverse++) = i;
	}
	return (*traverse/a_size);
}

int main()
{
   double a[] = {
     0.1,-1.2,2.3,-3.4,4.5,-5.6,6.7,-7.8,8.9
   };
   cout << average(a, 9) << "\n";
   system("Pause");
}

Last edited on
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

double average(double* a, int a_size)
{
	double accum = 0.0;
	for(int i = 0; i < a_size; ++i)
	{
		accum += *(a++);
	}
	return (accum / (double)a_size);
}

int main()
{
	double a[] = {
		0.1,-1.2,2.3,-3.4,4.5,-5.6,6.7,-7.8,8.9
	};
	int sz = sizeof(a) / sizeof(double);
	cout << average(a, sz) << "\n";
	cin.get();
	return 0;
}

didn't test code so it might have mistakes.
it worked thanks
Topic archived. No new replies allowed.