#include <iostream>
#include <string>
using namespace std;
class doubleArray {
private:
double * _theArray;
int _size;
public:
doubleArray()
{
_size = 0;
_theArray = new double [_size];
_theArray[0] = NULL;
}
doubleArray(int size)
{
_size = size;
_theArray = new double[_size];
for (int i = 0; i < _size; i++)
{
_theArray[i] = 0;
}
}
void setElement(double input, int i)
{
_theArray[i] = input;
}
double getElement(int element)
{
return _theArray[element];
}
double getAvg()
{
double sum = 0,
avg = 0;
for (int i = 0; i < _size; i++)
{
sum = sum + _theArray[i];
}
avg = (sum / _size);
return avg;
}
~doubleArray()
{
delete [] _theArray;
}
};
void displayArr(doubleArray, int size);
int main()
{
int arrSz;
double input,
avg;
cout << "How many numbers do you want to store? ";
cin >> arrSz;
doubleArray arr(arrSz);
cout << endl << "Enter the " << arrSz << " numbers:" << endl;
for (int i = 0; i < arrSz; i++)
{
cout << "Number " << i << ": ";
cin >> input;
arr.setElement(input, i);
}
displayArr(arr, arrSz);
avg = arr.getAvg();
cout << endl << "The average of those values is " << avg << endl;
system ("pause");
return 0;
}
void displayArr(doubleArray a, int size)
{
cout << endl << "Here are the values you entered:" << endl;
for (int i = 0; i < size; i++)
{
cout << "Number " << i << " : " << a.getElement(i) << endl;
}
}
Now here he the specific member function on its own:
double getAvg()
{
double sum = 0,
avg = 0;
for (int i = 0; i < _size; i++)
{
sum = sum + _theArray[i];
}
avg = (sum / _size);
return avg;
}
And here is the function's call on its own:
avg = arr.getAvg();
I've gone through the debugger, and the issue is that the variable _theArray[i] is not giving me the correct values. Now that I've figured out that this is the issue, I can't manage to figure out why it's doing this.
Here is the output this code is giving:
Quote
How many numbers do you want to store? 3
Enter the 3 numbers:
Number 0: 1
Number 1: 2
Number 2: 3
Here are the values you entered:
Number 0 : 1
Number 1 : 2
Number 2 : 3
The average of those values is -2.65698e+303
Enter the 3 numbers:
Number 0: 1
Number 1: 2
Number 2: 3
Here are the values you entered:
Number 0 : 1
Number 1 : 2
Number 2 : 3
The average of those values is -2.65698e+303
As you can see, the values for the array are set, but seem to be incorrect when it comes to using them to find the average. It would be greatly appreciated if someone could help point out my error. Thanks in advance.

New Topic/Question
Reply




MultiQuote




|