inf result to calculate standard deviation

"Write a program that takes its input from a file of numbers of type double. The program outputs to the screen the average and the standard deviation of the numbers in the file."

I'm a beginner when it comes to programming. Below is my code for the above question; when I execute it then I get the result "inf", instead of the standard deviation.

My input file, numbers.dat, contains the following information:

n1 = 45.6
n2 = 60.9
n3 = 78.7
n4 = 15.1

And outputs:

The average of all the numbers in numbers.date is: inf

PLEASE HELP.

#include <iostream>
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <cmath>

int main()
{
using namespace std;
ifstream in_stream;
ofstream out_stream;
out_stream.setf(ios::fixed);

double n1, n2, n3, n4, sum = (n1 + n2 + n3 + n4), total = 4;
in_stream >> n1 >> n2 >> n3 >> n4 >> sum >> total;
out_stream << "The average of all the numbers in numbers.dat is: "<< (sum / total);
in_stream.close( );
out_stream.close( );
return (0);

double average = (sum / total);
in_stream >> average;
out_stream << "The distance of n1 in numbers.dat file is: "<< pow(n1 - average, 2);
out_stream << "The distance of n2 in numbers.dat file is: "<< pow(n2 - average, 2);
out_stream << "The distance of n3 in numbers.dat file is: "<< pow(n3 - average, 2);
out_stream << "The distance of n4 in numbers.dat file is: "<< pow(n4 - average, 2);

double sumDist = pow(n1 - average, 2) + pow(n2 - average, 2) + pow(n3 - average, 2) + pow(n4 - average, 2);
in_stream >> sumDist;
out_stream << "The sum of all the data points in numbers.dat file is: "<< sumDist;

double stdDev = sqrt(pow(sumDist, 2)/total);
in_stream >> stdDev;
out_stream << "The standard deviation of all the numbers in numbers.dat is: "<< stdDev;

in_stream.close( );
out_stream.close( );
}
Last edited on
double n1, n2, n3, n4, sum = (n1 + n2 + n3 + n4),
Variables don't work like this. n1...n4 don't have proper values in them yet, so you shouldn't be assigning a result to sum yet.

1
2
double average = (sum / total);
in_stream >> average;

Two issues here:
(1) as mentioned before, you're attempting to use sum before it has a valid value.
(2) You attempt to calculate sum, but them you immediately overwrite it by doing in_stream >> average.

You might be thinking this is like mathematical notation, where variables are like placeholders to be filled in. Sadly, this is not the case in most programming languages.

Assign correct values to n1, n2, n3, n4. And THEN calculate the sum, average, etc.
Last edited on
Topic archived. No new replies allowed.