The data file sp05HWaveragesData.txt contains several lines of data. Each line o
ID: 3870523 • Letter: T
Question
The data file sp05HWaveragesData.txt contains several lines of data. Each line of data consists of an integer followed by a series of floating-point values all separated by space. The integer indicates the number of floating-point numbers that follow.
A sample data file might look like the following:
Write a program that will calculate the average for each line of data. The averages should be stored in the file sp05HWaverages.txt with one average per line. All averages should be stored with 15 decimal places of precision.
Please give answer in C++ format.
Explanation / Answer
#include <iostream>
#include <fstream>
#include<iomanip>
using namespace std;
int main()
{
//for reading
fstream inFile("sp05HWaveragesData.txt", ios_base::in);
//for writing
ofstream outFile;
outFile.open ("sp05HWaverages.txt");
//declaration
int n;
float average;
float sum=0,num;
//reading data from file
while (inFile >> n)
{
//iterate n times
for(int i=0; i<n; i++)
{
inFile >> num;
sum+=num;
}
//write data to file
outFile<<fixed<<setprecision(15)<<(sum/n)<<endl;
}
//closing input and output files
outFile.close();
inFile.close();
return 0;
}
sp05HWaveragesData.txt
5 5.7 8.7 4.9 6.72 6.41
9 2.1 1.99 2.01 1.8734 1.746 1.914 2.00345 1.70 1.69
3 28.4323345 28.499234 28.432451
OUTPUT:
sp05HWaverages.txt
6.486000061035156
5.495205402374268
44.940288543701172
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.