Click here to Skip to main content
15,844,498 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have to write a code to calculate the arithmetic , geometric and harmonic mean for 2 positive real numbers . I wrote :

#include <stdio.h>
#include <math.h>
int main()
{
    double num1, num2;
    float avg;
    float squareroot;
    float mharmonic;
    scanf("%lf %lf",&num1,&num2);

    avg= (float)(num1+num2)/2;

    printf("arithmetic mean is %lf\n" , avg);
    
    squareroot = sqrt(num1*num2);
    
    mharmonic = (2*(num1*num2)/num1+num2);
    
    printf("Geometrical mean is %lf\n" , squareroot);
    
     printf("Harmonic mean is %lf\n" , mharmonic);
    
    return 0;
}


is working fine for arithmetic and geometrical mean but did not give the correct result for the harmonic mean. I searched the internet and it s correct forumla but dont undestand why its not giving the correct result

What I have tried:

i searched for formula of harmonic mean and i found that one but it s not working
Posted
Updated 18-Nov-22 23:36pm

The harmonic mean is
the reciprocal of the arithmetic mean of the reciprocals of the given set of observations
And since the arithmetic mean of the reciprocals is ((1 / num1) + (1 / num2)) / 2 you want t5he reciprocal of that.
So try this:
C
mharmonic = 2 / ((1 / num1) + (1 / num2));
I'd write a function that took an array and the number of elements in it, and returned the result of the generic collection rather than hard coding it like that though - much more flexible in the long run, as well as easier to read!
 
Share this answer
 
Comments
Pascal Vlad 19-Nov-22 3:57am    
thank you
OriginalGriff 19-Nov-22 4:02am    
You're welcome!
CPallini 19-Nov-22 6:41am    
5.
I would suggest two small changes. The data types should be uniformly double and in the formula a bracket is set incorrectly.
C++
// float squareroot;
double squareroot;
// float mharmonic;
double mharmonic;

// ...

// mharmonic = (2 * (num1*num2) / num1 + num2);
mharmonic = (2*num1*num2) / (num1 + num2);

The formula works even if one of the two values is zero. In any case: If at least one of the quantities to be averaged is zero, the harmonic mean is to be defined as zero. Of course, this would have to be implemented in the program.
 
Share this answer
 
v2
Comments
CPallini 19-Nov-22 6:41am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900