2
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?

1
  • 11
    double avgTemp = std::accumulate(temps,temps+n,0.0) / n; assuming temps is a bunch of temperatures stored as floating point values. Commented May 30, 2012 at 23:17

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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];

Comments

1

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];

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.