Reputation: 3
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
Upvotes: 0
Views: 72
Reputation: 40160
Since 1
and n
are int
s, 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);
}
Note that I've answer in C++. C and C++ are two separate languages and you should choose which one to use beforehand.
Upvotes: 4
Reputation: 844
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);
Upvotes: 2