Creating a function the geometric (compounded) mean return

Hi, I am new to C++ (as you may be able to tell). I have been working on a project, and have a source code file with my functions definitions for use in the main source code file. One of these functions is the geometric mean function which I have programmed as follows:

1
2
3
4
5
6
7
8
9
10
11
  double geom(const double ret[], int n)
{
    double prod = 1;
    for (int i=1; i<=n; i++)
    {
        prod = prod*(ret[i]+1);
    }
    return prod;
    //double geomean = pow(prod, (double)1/n) - 1;
    //return geomean;
}


Here, ret[] is an array of returns (doubles varying around 0).
I have found the issue lies in the un-commented section of the code, which keeps returning 0 when I build and run(once fixed I will run the commented code also).

I would really appreciate if anyone could shed light on this. Let me know If there is information I need to provide that I have not.

Thank you
Arrays in C/C++ and related languages start at index 0, so
for (int i=1; i<=n; i++)
should be
for (int i=0; i<n; i++)


With the corrected indexing in the for loop, you then want just
prod *= ret[i];


Since 1.0 is a double constant, you can just
return pow( prod, 1.0/n );
Brilliant, thank you! I should've realized this myself, thanks for explaining it so clearly.

Topic archived. No new replies allowed.