writing a function to calculate an average

G

gaga

hi guys,
a part of my program requires me to calculate an average of items that
are sold. the easiest way to do that would be writing a function, but
im having trouble making up the parameters. if you can point me which
elements to use when performing such a task, i would really appreciate
it. thanks
 
G

Gianni Mariani

gaga said:
hi guys,
a part of my program requires me to calculate an average of items that
are sold. the easiest way to do that would be writing a function, but
im having trouble making up the parameters. if you can point me which
elements to use when performing such a task, i would really appreciate
it. thanks

Average is equal to the sum of a set of values divided by the number in
the set.

In your API, how are you presented with the set of values ? Are they in
an array, a file or there is no distinct set so your computation is
disjoint over the execution ?

Anyhow, once you have the sum and the count, you can easily compute the
average with a template like so:

template <typename T>
T average( const T & sum, unsigned long count )
{
return sum / count;
}
 
J

James Kanze

Average is equal to the sum of a set of values divided by the number in
the set.
In your API, how are you presented with the set of values ? Are they in
an array, a file or there is no distinct set so your computation is
disjoint over the execution ?
Anyhow, once you have the sum and the count, you can easily compute the
average with a template like so:
template <typename T>
T average( const T & sum, unsigned long count )
{
return sum / count;
}

You don't want to write a template unless you really have to.
On the other hand, this can be done in a single expression using
functions in the standard library:

average = std::accumulate( begin, end, 0.0 ) /
std::distance( begin, end ) ;

Of course, if the values are floating point, and there are more
than a very few, the results could easily be wrong. Getting an
even moderately accurate sum of a sequence of floating points is
non-trivial.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top