Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that takes its input from a file of numbers of type double. The

ID: 3761240 • Letter: W

Question

Write a program that takes its input from a file of numbers of type double. The program outputs to the screen the average and standard deviation of the numbers in the file. The file contains nothing but numbers of type double separated by blanks and/or line breaks. The standard deviation of a list of numbers n1, n2, n3, and so forth is defined as the square root of the average of the following numbers: (n1 a) 2 ,(n2 a) 2 ,(n3 a) 2 and so forth The number a is the average of the numbers n1, n2, n3, and so forth. Your program should read input from a file called stdDev. Hint: Write your program so that it first reads the entire file and computes the average of all the numbers, and then closes the file, then reopens the file and computes the standard deviation. C++

Explanation / Answer

1 way

#include <iostream>
#include <cstdlib>   
#include <fstream>
using namespace std;
int main()
{
ifstream input;
char name[13];
double value = 0, average;
double sum = 0;
int count = 0;
cout << "Enter a file name. 12 characters or less, please."
<< endl;
cin >> name;
input.open(name);
if(!input)
{
cout << "Cannot open file " << name << " Aborting." << endl;
exit (1);
}
input >> value;
while(input)
{
count=count+1;
sum = sum + value;
input >> value;
}
average = sum / count;
cout.setf(ios::showpoint);
cout.setf(ios::fixed);
cout.precision(4);
cout << "Average of " << count << " numbers is " << average
<< endl;
return 0;
}


2nd way
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
int RecCount=0;
int main()
{
double variance =0,standdev=0;
string myfilename, str;
myfilename = "test.txt";
ifstream inFile;
inFile.open(myfilename.c_str());
if (!inFile)
{
cout <<"Error opening file " << endl;
system("pause");
return -1;
}
int elmAdditons=0,elm=0,elmPrev=0;
cout<<"Numbers In The File As Following"<<endl;
while (!inFile.eof())
{
getline(inFile,str);
cout<<str<<endl;
elm =atoi(str.c_str());
if(RecCount>0)
{
elmAdditons+= (elm-elmPrev)*(elm-elmPrev);
}
elmPrev=elm;
RecCount++;
}
variance=( double) elmAdditons/RecCount;
standdev=sqrt(variance);
cout<<"Variance Is "<<variance<<endl;
cout<<"standard deviation Is " <<standdev<<endl;
getchar();
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote