435,028 Members | 1,869 Online
Need help? Post your question and get tips & solutions from a community of 435,028 IT Pros & Developers. It's quick & easy.

# writing a function to calculate an average

 P: n/a 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 Apr 5 '07 #1
4 Replies

 P: n/a 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 You can find some advice here: http://www.parashift.com/c++-faq-lit...t.html#faq-5.2 Apr 5 '07 #2

 P: n/a 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 T average( const T & sum, unsigned long count ) { return sum / count; } Apr 5 '07 #3

 P: n/a You can find some advice here:http://www.parashift.com/c++-faq-lit...t.html#faq-5.2 You guys are funny... :) Apr 6 '07 #4

 P: n/a On Apr 6, 1:04 am, Gianni Mariani 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 Apr 6 '07 #5

### This discussion thread is closed

Replies have been disabled for this discussion.