0

I might wonder if I have an int vector like this and I want to achieve the averagevalue for Element 0-8 wich is ((1+2+3+4+5+6+7+8+9) / 9) = 5

What method could be used for this ?

std::vector<int> Number(10);

Number[0] = 1;
Number[1] = 2;
Number[2] = 3;
Number[3] = 4;
Number[4] = 5;
Number[5] = 6;
Number[6] = 7;
Number[7] = 8;
Number[8] = 9;
Number[9] = 10;
Number[10] = 11;

4
Contributors
5
Replies
6
Views
8 Years
Discussion Span
Last Post by Jennifer84
Featured Replies
  • 2

    were you looking for a standard library function? like [B]std::accumulate[/B] ( in header [B]<numeric>[/B] ) [CODE]// vec is a std::vector<int> and N <= vec.size() int sum = std::accumulate( vec.begin(), vec.begin()+N, 0 ) ; // average == sum / double(N)[/CODE] Read More

0

If you have 9 as the number of elements you are interested in for the average, I would set up a sum variable, initialize it to 0, then set up a loop that repeats 9 times. Each trip through the loop would access a different element of the vector (design the loop so that the loop control variable is the index of the element you want). Add the value of that element to the sum variable. After the loop, divide the sum variable by 9.

2

were you looking for a standard library function?
like std::accumulate ( in header <numeric> )

// vec is a std::vector<int> and N <= vec.size()
int sum = std::accumulate( vec.begin(), vec.begin()+N, 0 ) ;
// average == sum / double(N)
Comments
nice one
Useful function.
0

were you looking for a standard library function?
like std::accumulate ( in header <numeric> )

// vec is a std::vector<int> and N <= vec.size()
int sum = std::accumulate( vec.begin(), vec.begin()+N, 0 ) ;
// average == sum / double(N)

Not bad, I didn't realize that function existed. I thought you had to write your own!

0

Not bad, I didn't realize that function existed. I thought you had to write your own!

If the purpose of the program is to teach you how to calculate an average, you do need to write your own.

0

The Accumulative function seem to be very good. Happy that it did exist such a function.
thanks :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.