Homework: Cout incorrectly handling a return value of 0.0 from a class method
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 st开发者_C百科ored.
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. (=
Divide-by-zero is well-defined to be positive or negative infinity. By default this displays as
Inf
or
-Inf
(at least on my machine).
setprecison
messes this up, see this other question.
average()
has divided something by zero and got minus infinity, and that's how cout
has displayed it.
You failed to show the average method but my guess is that you do a divide by zero in there. Wackiness ensues.
精彩评论