Write a program that takes its input from a file of numbers of type double. The
ID: 3665834 • 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 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 x1, x2, x3, and so forth is defined as the square root of:
((x1 – a)2 + (x2 – a)2 + (x3 – a)2 + ...) / (n - 1)
Where the number a is the average of the numbers x1, x2, x3, and so forth and the number n is the count of how many numbers there are.
Your program should take file name as input from the user.
A session should look like the following example (including whitespace and formatting), with a possibly number in the output:
The string printed by the program should include a newline at the end, but no other trailing whitespace (whitespace at the end of the line).
The standard deviation must be displayed to exactly three digits after the decimal point.
Explanation / Answer
#include <fstream>
#include <iostream>
#include <iomanip>
#include "Stats.h"
#define INFILE "InputDoubles.txt"
#define WIDTH 8
int main( )
{
using std::cin;
using std::cout;
using std::endl;
using std::setw;
cout << "~~~ Standard deviation calculator ~~~ ";
cout << " Reading input from " << INFILE << "... ";
std::ifstream fin(INFILE);
if (fin.fail( ))
{
cout << "Failed to open input file. Exiting. ";
exit( 1 );
}
ncoop::Dataset data;
double next;
while ( fin >> next )
{
data.addData( next );
}
cout << endl <<" Number of values:" << setw(WIDTH) << data.N( ) << endl <<
"Sum:" << setw(WIDTH) << data.Sum( ) << endl <<
"Mean:" << setw(WIDTH) << data.Mean( ) << endl <<
"Variance:" << setw(WIDTH) << data.Variance( ) << endl <<
"Standard deviation:" << setw(WIDTH) << data.StdDev( ) << endl << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.