When declaring an array, you can't have a variable for the size of the array. You must have a constant inside to specify the number of elements in an array.
So for example.
You can't do anything like this
1 2
|
int x=5;
int myarray[x]; //<-NO
|
The way that we instead approach this is by allocating memory the size of the array we need. Sounds complicated, but it's really not.
For the fixed version of the above sample, we'd do
1 2
|
int x=5;
int * myarray = new int[x]; <--this is fine
|
However there is one issue with this piece of code that I just posted.
Whenever you use new, you must use delete when you're done using that data. If you don't delete after you use new, you will have memory leaks which will break your program.
so you would change the code to
1 2 3 4 5
|
int x=5;
int * myarray = new int[x];
//do stuff with myarray
delete[] myarray; //clean up allocated memory
|
So your code would change to
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
|
#include <iostream>
using namespace std;
double avgVal(int, int);
int main()
{
int amountOfCases;
cout << "Please enter the number of cases" << endl;
cin >> amountOfCases;
cout << "Please enter " << amountOfCases << " numbers" << endl;
int * numbers = new int[amountOfCases];
int sum = 0;
for (int i = 0; i<amountOfCases; i++)
{
cin >> numbers[i];
sum = sum + numbers[i];
}
cout << avgVal(sum, amountOfCases);
delete[] numbers;
system("pause");
return 0;
}
double avgVal(int sum, int amountOfCases)
{
return sum / (double)amountOfCases;
}
|
You'll notice I also changed your avgVal function to divide by amountOfCases converted to a double. The reason I did this is because otherwise, since you're performing an operation dividing an integer by an integer, you will get an integer. Ex. (5/2 should be 2.5, but as an integer 5/2 = 2 - It always rounds down to the nearest whole #)
Since your function is a double function, I figured you wanted to return a decimal if the average was a decimal.