C Problem Power Plant Data The data file power1dat contains
C++ Problem:
Power Plant Data. The data file power1.dat contains a power plant output in megawatts over a period of 10 weeks. Each row of data contains 7 floating-point numbers that represent 1 week\'s data. In developing the following programs, use symbolic constants NROWS and NCOLS to represent the number of rows and columns in the array used to store the data.
Write a function to compute and return the average value in a two-dimensional vector of type double. Assume that the corresponding function prototype is
double avgVec(const vector<vector<double> > &x);
This is a screenshot of the data file opened in notepad:
Solution
#include<bits/stdc++.h>
using namespace std;
int m,n;
double avgVec(const vector<vector<double> >& x)
{
double sum=0;
double count=0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// Add an element to sum
sum+=x[i][j];
count++;//increment count of number
}
}
double avg=sum/count; //Calculate average
return avg;
}
int main(int argc, char const *argv[])
{
vector<vector<double> > matrix; //create 2-D vector
ifstream file(\"power1.dat\",ios_base::in);//open file
file>>m;//no of columns
file>>n;//no of rows
for (int i = 0; i < m; i++) {
vector<double> row; // Create an empty row
for (int j = 0; j < n; j++) {
double d=0;
file>>d;
row.push_back(d); // Add an element (column) to the row
}
matrix.push_back(row); // Add the row to the main vector
}
double resultavg=avgVec(matrix);
cout<<\"Avearge is \"<<resultavg;
return 0;
}
===========================================
For simplicity i took file as
power1.dat
4 4
4 4 4 4
4 4 4 4
4 4 4 4
4 4 4 4
output:
Avearge is 4

