Ziv har-lev
Ziv har-lev

Reputation: 3

pow function gives unwanted result c

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

Answers (2)

YSC
YSC

Reputation: 40160

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.

Upvotes: 4

Yuriy Orlov
Yuriy Orlov

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

Related Questions