C++ function for average not working

hi

i am trying to make a function to display an average of an array. I am using Microsoft Visual C++ Express 2010.

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
24
25
26
27
#include <iostream>
using namespace std;

float avg(int[], int);

int main()
{
	int a[] = {2,4,3,6};
	int size = sizeof(a) / sizeof(int);

	//cout << size << endl << endl;
	cout << "avg(a,s) = " << avg(a,size) << endl;

	system("pause");
	return 0;
}

float sum(int a[], int s)
{
	float sum = 0;
	float avg = 0;
	for (int i = 0; i < s; i++) {
		sum = float(sum + a[i]);
	}
	avg = (sum / s);
	return avg;
}


it displays this error
1
2
1>main.obj : error LNK2019: unresolved external symbol "float __cdecl avg(int * const,int)" (?avg@@YAMQAHH@Z) referenced in function _main
1>D:\C++ ... \Debug\exercise 6.3.exe : fatal error LNK1120: 1 unresolved externals
i got it :)
doforumda>int size = sizeof(a) / sizeof(int);

I'm newbie on this forum, however, I've already seen one interesting template to find a size of an array:

1
2
3
4
template <typename T, size_t N>
size_t sizeof_array( const T (&a) [ N ] ) {
    return N;
}

been posted by Duaos or Disch (can't resolve 'em).

As automatic arrays with a constant size are of different types for different sizes in C++, sizeof_array template instants different functions for arrays of different sizes received as arguments and returns the template parameter used to instant the function, and the parameter itself is a size of an array known by compiler!

This template is so cute (!) that I can't help recommend you to make use of one in your programs in the future instead of unsafe int size = sizeof(a) / sizeof(int);.

The other thing, one hardly could argue with Duaos, is you ought not to use system calls. All you need is to run your program under console.
Topic archived. No new replies allowed.