First, this is homework, so I can not dynamically allocate memory for an array of any size, and I can not use a vector.
I have a class which includes a double array holding 30 elements, and two other variables to keep track of how many elements have been added and the max number of elements that can be stored.
There are several methods that return the highest, lowest, average, and total from the elements in the array. An example of one of the methods is…
double Stats::sum() const
{
double sum = 0.0;
for (unsigned short i = 0; i < nElements; ++i)
sum += stats[i];
return sum;
};
In my main() function I have a cout statement…
cout << "\nTotal rainfall for " << MonthlyRainfall.size() << " months is "
<< MonthlyRainfall.sum() << " inches.\n";
When there are values in the array, the output is what I expect…
Total rainfall for 1 months is 1.5 inches.
However, when there are no values in the array (the method returns 0.0), but the output looks like…
Total rainfall for 0 months is -1.$ inches.
Can anyone help me understand what’s happening in the cout statement that’s causing the 0.0 returned by my method to output as it is?
Note: At the beginning of the main() function, the following statement is executed to format the decimal output. cout << fixed << showpoint << setprecision(1);
Update
I guess it was late and I was calling the average() method instead of sum(). I have fixed it and you also pointed out that I needed to make a couple changes to the average method to ensure a divide by 0 is not happening. (=
average()has divided something by zero and got minus infinity, and that’s howcouthas displayed it.