Nov 15, 2010 at 10:44pm UTC
Hi,
I'm pretty bad at using c++ and need some help writing a program that uses a call-by-value function to calculate the geometric mean of an array for my class. We are using Borland c++. Below is what I have come up with so far, if you could point me in the right direction that would be great !
Thanks so much
#include <stdio.h>
#include <math.h>
#define N 10
float calcGeoMean(float x[], int n);
int main(void)
{
float data[N] = {2.4, 6.7, 7.3, 1.2, 4.9, 5.4, 2.3, 5.4, 3.1, 8.5};
float geoMean; /* geometric mean */
float geoProduct
geoMean = calcGeoMean(x[], n);
printf("The geometric mean is %f\n", geoMean);
return 0;
}
float calcGeoMean(float x[], int n)
{
double geoProduct = 1;
float geoMean;
int i;
while (i<n) {
geoProduct= geoProduct*x[i];
i++;
}
geoMean = pow(geoProduct, 1/(double)n);
return geoMean;
}
Also, the formula for a geometric mean is the product of the numbers raised to the 1/n power.
Nov 15, 2010 at 10:49pm UTC
What's the problem that you are having?
Nov 15, 2010 at 10:55pm UTC
When I compile the program I get a declaration syntax error for the line:
geoMean = calcGeoMean(x[], n);
and I'm not too sure if my function actually works
Nov 15, 2010 at 10:57pm UTC
When you are passing an array, just use the name, you don't need the "[]".
In your function, you aren't initializing i so it will be garbage.
Nov 15, 2010 at 11:04pm UTC
I have change my code to this but it still does not work. I'm not too sure what the arguments are supposed to be for the function call.
#include <stdio.h>
#include <math.h>
#define N 10
float calcGeoMean(float x[], int n);
float calcHarmMean(float x[], int n);
int main(void)
{
float data[N] = {2.4, 6.7, 7.3, 1.2, 4.9, 5.4, 2.3, 5.4, 3.1, 8.5};
float geoMean; /* geometric mean */
float harmMean; /* harmonic mean */
float geoProduct
geoMean = calcGeoMean(data, geoMean);
printf("The geometric mean is %f\n", geoMean);
printf("\nThe harmonic mean %f\n", harmMean);
return 0;
}
float calcGeoMean(float data[], int n)
{
double geoProduct = 1;
float geoMean;
int i=0;
while (i<n) {
geoProduct= geoProduct*data[i];
i++;
}
geoMean = pow(geoProduct, 1/(double)n);
return geoMean;
}
Nov 15, 2010 at 11:05pm UTC
Could you be more specific on how it "does not work"?
Nov 15, 2010 at 11:06pm UTC
sorry, when I try to compile it, I still get a declaration syntax error.
Nov 15, 2010 at 11:08pm UTC
You are missing a ';' after float geoProduct
Btw, use [co de][/code] tags in the future, thanks.