Need some help computing the geometric mean of an array

this is what I have so far...

i'm not really sure why i'm suppose to use pow

``````include math.h
include

int geomean(int *myarray, int count)
{
double geo = 0;
double count = (double)count;
for(int k=0; k < count; k++)
{
geo+= myarray[k] * myarray[k];
geo = pow();
}
}``````

## All 13 Replies

What's the equation for a geometric mean?

So to find the geometric mean of 3, 4 and 18, we would multiply 3 x 4 x 18. This would give us 216. We would then take the cubic root (cubic root because there were three original numbers). The answer would be 6. In other words, since 6 x 6 x 6 = 3 x 4 x 18, 6 is the geometric mean of 3, 4 and 18.

And how do you plan on taking the cubic root? Did you look up what `pow()` does?

got this now

``````include math.h
include stdio.h

int geomean(int *myarray, int count)
{
double geo = 0;
double count = (double)count;
for(int k=0; k <= count; k++)
{
geo*= myarray[k];
}
return geo = pow(geo,1/3);
}``````

ok with some more debugging I have this now

``````#include <stdio.h>
#include <math.h>

int geomean(int *myarray, int count)
{
double geo = 0;
int k;
for(k=0; k < count; k++)
{
geo = geo * myarray[k];
}
return geo = pow(geo,1/3);
}``````

but for an array inputed of 20,6,9 i get a return value of 1, which is wrong.... ideas?

Test the following line: `printf("%d\n",1/3);` If you provide integers, an integer division will be performed.

Use a cast to make the numerator, denominator, or both into doubles.

it prints out a 0

Right, so what's anything to the power of 0... = 1

Change 1/3 to (double)1/3

Hello ilinan87,
You declared double geo=0. So on multiplying it with the numbers will give zero only. That's why you are not getting the required answer. Initialize geo as 1.

``````int geomean(int *myarray, int count)
{
double geo = 1;
int k;
for(k=0; k < count; k++)
{
geo = geo * myarray[k];
}
return geo = pow(geo,1/3);
}``````

You declared double geo=0

Yes, that's very true. Even if he had, though, the result would still be something to the power zero, so that's where the 1 comes from.

Hello Jonsca and ilinan87,
1/3 is zero since both are integers. It works fine when 1/3 given as 0.333 or 1.0/3.0 in the pow() function.

is there any simple code for geometric mean...?

is there any simple code for geometric mean...?