There are two things happening here which are getting confused.
The
mean (or
average) is always computed the same way, regardless of how many items there are:
(sum of all elements) / (number of elements)
The code example above is also
filtering the array. It is only finding the average of the elements of the array that are
odd numbers, and ignoring those elements that are not odd.
For example, given the array:
{ 1, 2, 3, 4, 5, 6 }
We see that there are six elements. The average is (1+2+3+4+5+6)/6 = 3.5.
However, if we only want the odd elements, our array is effectively changed to:
{ 1, 3, 5 }
Three elements. Average = (1+3+5)/3 = 3.0.
This filter step could be done separately, but the two algorithms are combined to work together.
1 2 3 4 5 6 7 8 9 10 11
|
for (i=0; i<n; i++) // loop through EVERY item in the array
{
if (arr[i]%2==1) // but only continue if the item is ODD
{
sum=sum+arr[i]; // update our sum (with the odd number)
count++; // update our count (of odd numbers)
}
}
// the average is the (sum of the odd numbers) / (count of odd numbers)
return sum*1.0/count;
|
That last line also needs a little explanation. In C and C++, the solidus (division operator) works over different types. If both types are integers, the result of the division is also an integer (you get integer division). Hence, 21/6 is exactly 3, an integer.
However, if at least one of the operands is a floating point type, the result of the division is also floating point. Hence, 21.0/6 is exactly 3.5, a float.
Your function returns a float, so regardless of whether you perform integer or floating-point division you get a float, which is why you get 45.0 as a result instead of the integer 45.
To force one of the operands to be float, simply multiply a floating value in. The identity value 1.0 is a good one.
As a matter of technical detail, since the function returns
float
and not
double
, that 1.0 should be
1.0f
, indicating a float and not a double.
12 13
|
return (sum*1.0f)/count;
}
|
Hope this helps.
[edit]
Fixed stupid typos.
And autocorrects.