In: Computer Science
How do I do this:
Write a program that can read a text file of numbers and calculate the mean and standard deviation of those numbers. Print the result in another text file. Put the result on the computer screen. EACH LINE OF THE PROGRAM MUST BE COMMENTED!
Hi, You have not mentioned about programming language.
Please try to provide all details.
I have implementated in C++.
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
const int MAX_SIZE = 100;
// Pre: size <= declared size of the array argument
// Post: return the standard deviation first size array
elements
// Note: The divisor is the size, not size - 1 as some
// formulae call for.
double stdDev(double s[], int size);
// Pre: size <= declared size of the array argument
// Post: return the mean of the first size array elements
double average(double s[], int size);
int main()
{
// declaring an array of size 100
double s[MAX_SIZE];
// reading file name
string inputFile, outputFile;
cout<<"Enter input file name: ";
cin>>inputFile;
cout<<"Enter output file name: ";
cin>>outputFile;
// opening files
ifstream inFile(inputFile.c_str());
if(inFile.fail()){
cout<<"ERROR in opening input file"<<endl;
return -1;
}
ofstream outFile(outputFile.c_str());
int size = 0;
int num;
while(inFile>>num){
s[size] = num;
size = size + 1;
}
// calculating mean
double mean = average(s, size);
cout<<"Mean : "<<mean<<endl;
// calculating standard deviation
double stdDeviation = stdDev(s, size);
cout << "The Standard Deviation is: "<< stdDeviation
<< endl;
// writing in file
outFile<<"Mean: "<<mean<<endl;
outFile<<"Standard deviation:
"<<stdDeviation<<endl;
// closing files
inFile.close();
outFile.close();
return 0;
}
//Write the function header here…
double stdDev(double s[], int size)
{
double sumSquares = 0;
double avg = average(s, size);
//Write the for loop here…
for(int i=0; i<size; i++){
sumSquares += pow(s[i]-avg, 2);
}
return sqrt(sumSquares / size);
}
//Write the function header here…
double average(double s[], int size)
{
double sum = 0;
//Write the for loop here…
for(int i=0; i<size; i++)
sum += s[i];
return sum / size;
}