-
February 18th, 2007, 12:00 PM
#1
getting average!!
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
-
February 18th, 2007, 01:28 PM
#2
Re: getting average!!
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;
Good luck!
Gili
Please use code tags [code] [/code]
We would change the world, but God won't give us the sourcecode..
Undocumented futures are fun and useful....
_________
Gili
-
February 18th, 2007, 02:49 PM
#3
Re: getting average!!
thnx its working fine now
-
February 19th, 2007, 02:53 AM
#4
Re: getting average!!
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;
-
February 19th, 2007, 05:20 AM
#5
Re: getting average!!
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.
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();
}
Regards,
Pravin.
-
February 19th, 2007, 06:14 AM
#6
Re: getting average!!
Originally Posted by Pravin Kumar
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.
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();
}
Regards,
Pravin.
I suggest passing the vector by reference to avoid making a useless copy (especially if the vector holds many elements).
-
February 19th, 2007, 07:09 AM
#7
Re: getting average!!
Originally Posted by cilu
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;
1) accumulate is in <numeric>
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;
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|