Write a program in which the main() function a. Accepts an integer number from t
ID: 3650115 • Letter: W
Question
Write a program in which the main() functiona. Accepts an integer number from the user, N. Generates N random numbers between 0 and 1 and writes these out to a file called DataFile.txt.
b. Calls the function double myavg (int N) that reads in the stored numbers from DataFile.txt and returns their average value to main().
c. Calls a function called double mysd (int N, double Mean) that reads in the stored numbers, again from the file DataFile.txt, and returns their standard deviation to main(). Note that Mean is the mean value returned by myavg.
d. Writes out the returned average and standard deviation to the console and to a file called DataStats.txt
Explanation / Answer
please rate - thanks
#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
#include <cmath>
using namespace std;
double myAvg(int);
double mysd(int,double);
int main()
{int n,i;
ofstream out;
double average,sd;
srand(time(0));
cout<<"How many numbers: ";
cin>>n;
out.open("DataFile.txt");
for(i=0;i<n;i++)
out<<((double)rand()/(RAND_MAX))<<endl;
out.close();
average=myAvg(n);
sd=mysd(n,average);
out.open("DataStats.txt");
out<<"average="<<average<<endl;
out<<"standard deviation="<<sd<<endl;
cout<<"average="<<average<<endl;
cout<<"standard deviation="<<sd<<endl;
out.close();
system("pause");
return 0;
}
double myAvg(int n)
{int i;
ifstream in;
double num,sum=0;
in.open("DataFile.txt");
if(in.fail()) //is it ok?
{ cout<<"file did not open please check it ";
system("pause");
system ("exit");
}
for(i=0;i<n;i++)
{in>>num;
sum+=num;
}
in.close();
return sum/n;
}
double mysd(int n,double avg)
{int i;
ifstream in;
double num,sum=0,diff;
in.open("DataFile.txt");
if(in.fail()) //is it ok?
{ cout<<"file did not open please check it ";
system("pause");
system ("exit");
}
for(i=0;i<n;i++)
{in>>num;
diff=(num-avg);
sum+=(diff*diff);
}
in.close();
return sqrt(sum/n);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.