On Apr 6, 1:04 am, Gianni Mariani <gi3nos...@mariani.wswrote:
gaga wrote:
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;
}
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.
--
James Kanze (Gabi Software) email:
ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34