I wrote this before scrolling down the post to see you already found an answer but here it is for reference if it is needed.
I used a dynamic array so the user can enter as many numbers as they wish and then get the average
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 28 29 30 31 32 33 34 35 36 37 38
|
#include <new>
void getAverage(double a[], int size, int *pVar)
{
int tempHold = 0;
for (int n=0; n<size; n++) {
tempHold+=a[n];
}
*pVar = tempHold;
}
int main() {
double * userinput;
int arraySize=0;
int average=0;
cout << "How many numbers would you like to enter? ";
cin >> arraySize;
userinput=new (nothrow) double [arraySize];
if(userinput==0) { cout << "Couldn't allocate memory."; return 1; }
for(int n=0; n<arraySize; n++) {
cout << "Enter a number: ";
cin >> userinput[n];
}
getAverage(userinput, arraySize, &average);
cout << "The result is: " << average << endl;
delete [] userinput;
return 0;
}
|
Also, a neat trick (that doesn't work with dynamic arrays though) is that you can calculate the size of an array by doing this
sizeof(array) / sizeof(array type)
since we are working with doubles
sizeof(userinput) / sizeof(double)
this makes perfect sense if you know the size of a double is 8 bytes, the size of an array with 5 doubles is 40
40 / 8 = 5
and because, in your original code, you work with a static array, your averageCal function could be as this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void averageCal (double a[])
{
//initialize variables
double addition=0;
double average_ans = 0;
int size = sizeof(a) / sizeof(double);
for (int c = 0; c < size; c++)//for loop to add the numbers
{addition = addition + a[c];}//end of for loop
average_ans = addition / 5;//dividint the numbers by 5
cout << average_ans << endl;
}//end of function
|
which would require one less parameter for your function