C++ Finding the average of the numbers in an array
arrays, average, c++
Solution
This
for( k = 0; k < n; k++ )
{
/// here's the error.
/// You assign the new value to total as (total = total + total + temps[k])
total += total + temps[k];
}
avgTemp = total / n;
should be
for( k = 0; k < n; k++ ) { total += temps[k]; }
avgTemp = total / n;
or
for( k = 0; k < n; k++ ) { total = total + temps[k]; }
avgTemp = total / n;
Using the iterative summation would be even better. It allows to avoid the round-off errors.
avgTemp = temps[0];
for(k = 1 ; k < n ; k++) { total = (temps[k] + (double)(k-1) * total)/ (double)k; }
bames53 also gives a nice STL-based code in the comment.
Problem
``` for( k = 0; k < n; k++ ) { total += total + temps[k]; } avgTemp = total / n; ``` `temps` is my array that contains `n` elements. `avgTemp` stores the average of all the values in `temps`. k is just some integer to make my loop work. k, n, and total are already declared appropriately somewhere above. `total` keeps track of the total of the elements in the array. My exercise thing is telling me this is wrong. What am I doing wrong?