Write a program that takes its input from a file of numbers

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 n_1, n_2, n_3, and so forth, is defined as the squareroot of the average of the following numbers: (n_1 - a)^2, (n_2 - a)^2, (n_3 - a)^2, and so forth The number a is the average of the numbers n_1, n_2, n_3, and so forth. Write your program so that it first reads the entire file and computes the average of all the numbers, then closes the file, then reopens the file and computes the standard deviation. You will find it helpful to first do Programming Project 12.2 and then modify that program to obtain the program for this project.

Solution

#include <iostream>
#include <fstream>
#include<math.h>
using namespace std;
float standdv(float[], int);
int main()
{
std::fstream f(\"G:\\\\float.txt\",std::ios_base::in); //open the file make sure file is present in the given path.
float a[100]; //initialise the required array with required size
float n;   
int size=0;
while (f >> n) //read out the floats ne by one
{
a[size]=n; //store those floats into array
size++;
}
cout<<\"standard deviation is:\"<<standdv(a,size); //caluclate the standard deviation by calling the function

return 0;
}

float standdv(float a[], int size)
{
   //caluclating standard deviation.
   float mean=0.0, sum=0.0;
int i;
for(i=0; i<size;++i)
{
mean+=a[i];
}
mean=mean/size;
for(i=0; i<size;++i)
sum+=(a[i]-mean)*(a[i]-mean);
return sqrt(sum/size);
}

Example file content:-

3.7
7.8
1.2

example output:-

Standard deviation is:2.7207

 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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site