0

for an assignment i've been asked to write a program that calculates Geometric and arithmetic mean in regular c. i wrote this function:

double Geometric_mean(int number[], int n) //number[5]={1,2,3,4,5},n=5
{
    int i;
    double mean = 1;
    for (i = 0;i < n;i++)
    {
        mean =mean*number[i];
    }
    mean = pow(mean,1/n); //mean=120
    return(mean); //mean=1
}

i get the desired result before the pow turns it to 1 instead the of the desired 2.605

1
  • "calculates Geometric and arithmetic mean in regular c". So why did you tag C++?
    – Samidamaru
    Commented Nov 24, 2015 at 10:55

2 Answers 2

4

Since 1and n are ints, 1/n is an euclidean division whose result is 0 for any n > 1.

You should use a double division:

#include <cstddef>
#include <cmath>

double gmean(const int data[], std::size_t datasize)
{
    double product = 1.0;
    for (std::size_t i = 0 ; i < datasize ; i++)
    {
        product *= data[i];
    }
    return std::pow(product, 1.0/datasize);
}

Live example.

Note that I've answer in C++. C and C++ are two separate languages and you should choose which one to use beforehand.

1
  • 1
    I would prefer 1.0/n instead of the static cast
    – mch
    Commented Nov 24, 2015 at 10:31
2

You using integral division pow(mean,1/n); the result of 1/n is zero if n > 1. You should convert it to float or double :

pow(mean,1.0/n);

or

pow(mean,1/(double)n);
1
  • and why not 1.0/(double)n ??? Why forcing with a cast the compiler to do another cast? Of course, all are correct, but why to insist in using integers if the whole operation is floating point? Newbies get a better instruction if they learn from the beginning to distinguish floating point literals (numbers with an explicit decimal point) from integer literals (they don't have a dot) Commented Nov 24, 2015 at 18:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.