forthewinwin
forthewinwin

Reputation: 4755

C++ Finding the average of the numbers in an array

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?

Upvotes: 2

Views: 14899

Answers (5)

Jonathan Mee
Jonathan Mee

Reputation: 38959

As is mentioned in bames53's comment accumulate is really your best bet for solving this. Given n which is the size of the container and it which is either a pointer or iterator to the first element of the container, you can do this for arrays, dynamically allocated arrays, or vectors:

const auto avgTemp = accumulate(it, next(it, n), typename iterator_traits<remove_const_t<decltype(foo)>>::value_type{}) / n;

Live Example

Upvotes: 0

Viktor Latypov
Viktor Latypov

Reputation: 14467

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.

Upvotes: 7

Stephan
Stephan

Reputation: 1037

Your code is adding "total" to itself on every iteration, which is not what you want. You need to change:

total += total + temps[k];

to

total += temps[k];

Upvotes: 2

monokh
monokh

Reputation: 1990

When getting the sum of the numbers, you are adding the total to itself and then adding the next element.

total += total + temps[k];

should be:

total += temps[k];

Upvotes: 1

Mario Corchero
Mario Corchero

Reputation: 5575

First, total += temps[k]

+= Means total = total + temps[k] already

And By the way, Is total declared as float or double? Otherwise you are doing a integer Division.

Upvotes: 2

Related Questions