Friday, May 21, 2010

Basic C++ help?? plz?

2. Write 3 functions that (each) accept the following two items:





a) an array of floats of undetermined length.


b) an integer that represents the length of the array.





and return:





a) The mean of the array values


b) The minimum of the array values


c) The maximum of the array values





If u are unable to write the code, can u please atleast find a site that shows me how?? thanks

Basic C++ help?? plz?
In line with the first poster, I am not giving a full answer; however, there are ways to answer these questions using STL [1] (because I'm a perverse geek that likes to use STL for most anything :-P):





1. return accumulate(a.begin(), a.end(), 0.0) / a.size();


2. return *min_element(a.begin(), a.end());


3. return *max_element(a.begin(), a.end());





How to construct the container a, and deciding which headers to include, are left as exercises for the reader.





ETA: Of course, the _best_ answer does not involve constructing any containers at all (hint: a pointer is an iterator, and so is pointer + offset). However, I'm trying to be careful not to give away too much. :-P





ETA2 (this section heavily edited to sound more professional :-)): Because I wish to present a C++-style and const-correct approach, here's a complete solution for how to calculate the geometric mean (using STL and pointer-iterators), using the parameters as specified in the question.





double geometric_mean(double const* a, size_t n) {


return pow(accumulate(a, a + n, 1.0, multiplies%26lt;double%26gt;()), 1.0 / n);


}





To adapt the above for use in your assignment, you should:





1. Convert the function to use floats rather than doubles.


2. Make the function calculate the arithmetic mean [2], minimum, and maximum, as required. The first part of my message has some ideas for this, if your assignment allows the use of STL.


3. Change my one-letter variable names to something a little more meaningful, if you wish to avoid getting seriously penalised by your marker.
Reply:That sounds like a really neat HOMEWORK ASSIGNMENT!





Why don't you write it yourself (based on what you read in your text book)? It's really not that hard, and if you can't do something as simple as this, you don't deserve to pass your class.
Reply:float average(float *f, int size)


{


float sum = 0;


int i;


for (i = 0; i %26lt; size; ++i)


sum += *(f + i);


return (size %26gt; 0) ? sum / size : 0.0;


}





float min_value(....) see above function for parameters


{


float m = *f;


int i;


same style of for loop


but compare m with f[i] and assign f[i] to m if f[i] %26lt; m


return m;


}





similiar with maximum but reverse if check.





Hope this helps.


No comments:

Post a Comment