Monday, May 24, 2010

Help in c++ program?

i want to write a program that calculates arithmatic and geometric mean in c++ , so i need help

Help in c++ program?
You aren't very specific with your request. How will the numbers be input (e.g. entered at the console, constant array, from a file) into the program? Any particular number format (e.g. integers, scientfic notation, simple floating point, double precision, fractions, sequence range, symbolic)?





Do you have a start to your program that you could share? This would help answer some the questions above. Is this a homework problem? Do you simply need hints regarding the general concepts for a computing solution or specific help on how to code certain aspects?





The arithmetic mean is pretty straight forward; it's just the average of your input numbers. However, the geometric mean can be done in several ways. I recommend taking the log of each input number, adding each log (i.e. multiply), dividing (i.e. nth-root) by the number of items, and finally the anti-log. Below is a quick attempt:





#include %26lt;math.h%26gt;


#include %26lt;iostream%26gt;


using namespace std;


int main () {


double nums[] ={8.3, 7.5, 1.9, 6.2, 2.4}; // input numbers


int numCount = sizeof(nums); // number of elements


double arithmetic_mean=0.0, geometric_mean=0.0;


for (int counter=0; counter%26lt;numCount; counter++) {


arithmetic_mean += nums[counter];


geometric_mean += log(nums[counter]);


}


arithmetic_mean /= numCount; // calc average


geometric_mean = exp(geometric_mean/numCount); // calc e ^ nth-root


cout %26lt;%26lt; "arithmetic mean = " %26lt;%26lt; arithmetic_mean %26lt;%26lt; endl;


cout %26lt;%26lt; "geometric mean = " %26lt;%26lt; geometric_mean %26lt;%26lt; endl;


return 0;


}





Obviously, you'll want to substitute the appropriate input code for the nums[] array. Also, I assumed double precision calculations but you may have different requirements.


No comments:

Post a Comment