hi im stuck.
lets say i have
int count =6;
and make and array of
float n[6]={1,2,3,4,5,6},total,average;
and i want it to add all the numbers up
How would i do this in a loop?
NOT this way
n[0]+n[1]+n[2]+.... then /count
Printable View
hi im stuck.
lets say i have
int count =6;
and make and array of
float n[6]={1,2,3,4,5,6},total,average;
and i want it to add all the numbers up
How would i do this in a loop?
NOT this way
n[0]+n[1]+n[2]+.... then /count
Good luck!Code:
float sum = 0;
float n[6]={1,2,3,4,5,6}
for( int i = 0; i<count; ++i)
{
sum += n[i];
}
float average = sum/count;
Gili
thnx its working fine now
Or, with the use of accumulate
Code:#include <algorithm>
float n[6]={1,2,3,4,5,6}
float sum = std::accumulate(&n[0], &n[5], 0);
float avg = sum / 6;
Hello,
It is advantageous to use STL where the size of the array is bound with the data itself. Here is a sample code to evaluate the average of a vector array.
Regards,Code:float average(std::vector<float> array)
{
float sum = 0;
for (int count = 0; count < array.size(); count++)
sum += array[count];
return sum / array.size();
}
Pravin.
I suggest passing the vector by reference to avoid making a useless copy (especially if the vector holds many elements).Quote:
Originally Posted by Pravin Kumar
1) accumulate is in <numeric>Quote:
Originally Posted by cilu
2) the "end()" iterator has to be one past the last element
Code:float sum = std::accumulate(&n[0], &n[6], 0); // or (n,n+6,0.0f)
float avg = sum / 6;