15,844,498 members
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

Solution 1

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!

thank you
OriginalGriff 19-Nov-22 4:02am
You're welcome!
CPallini 19-Nov-22 6:41am
5.

Solution 2

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.

v2