Harmonic Mean Calculation result: "inf" unless I use small values

Hello,

I'm in my first programming class at college for my computer science major, yeah! It's a lot of fun learning C++, especially the problem I have right now, but I am at a loss as to how to procede.

I have written the harmonic mean formula based on the formula my professor gave me: n / ( 1/n1 + 1/n2 + 1/n3 + 1/n4 + 1/n5 )
"n" is the total number of integers entered
"n1" through "n5" are the values the user enters in the command prompt.

For some reason it is returning an infinite value when I print the results on the screen, unless I use small values. For example: 1 2 3 4 5 will work, but if I use the values my professor assigned us to test the program: 85 43 95 100 78, then it does not work. I remember something from class about this problem applied to something else meaning that the number was too big for the variable to hold, but I dont see how it could be too big. I have messed around with it for over 2 hours now, searched the web, but I haven't found anything that I could do differently. Does anyone see anything I could do differently?

Thanks in advance.

#include <iostream>
using namespace std;

int main()
{
int n1;
int n2;
int n3;
int n4;
int n5;

double d1 ;
double d2 ;
double d3 ;
double d4 ;
double d5 ;
double sumd ;
double hMean;

//Data Input
cout << "Enter 5 integers: ";
cin >> n1 >> n2 >> n3 >> n4 >> n5;

//Calculate Harmonic Mean
d1 = 1 / n1 ;
d2 = 1 / n2 ;
d3 = 1 / n3 ;
d4 = 1 / n4 ;
d5 = 1 / n5 ;
sumd = d1 + d2 + d3 + d4 + d5 ;
hMean = 5.0 / sumd ;

//Data Input
cout << "Harmonic Mean = " << hMean << endl ;

return 0 ;
}
Last edited on
Your problem (or one of them) arises from integer / integer = integer.
Thanks! I don't know how I missed that I had "1" instead of "1.0" That was my problem. Thanks again! Problem solved!
Topic archived. No new replies allowed.