3) Write a C++ program that calculates the average of measurements of Oak tree l
ID: 3677295 • Letter: 3
Question
3) Write a C++ program that calculates the average of measurements of Oak tree leaves. The measurements are
Follow the following requirements 1. Declare an array to hold the data in the main() program. 2. Write a function to read the data from the file into that array (ReadFile()) and call it from main(). The function should return TRUE if the file was successfully opened and read. It should return FALSE otherwise; i.e. if it encounters any problem. 3. Write a function called FindAve() that returns the average of the leaves' measurements stored in the array. Call this function from main() and pass it the array that contains the data. 4. Within main(), after data is read in and average leave length is calculated, write code that opens an output file named oakOut.txt and writes into it a statement that includes the calculated leaves average length value; something like this Average leaves length was calculated to be x.xxx.
Explanation / Answer
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
bool ReadFile(float data[]){
ifstream inFile;
char fileName[15];
cout<<"Enter file name: ";
cin>>fileName;
inFile.open(fileName);
if ( inFile.fail() )
{
return false;
}
//reading company name
string name;
float d;
getline(inFile,name);
cout<<name<<endl;
//reading employee name
getline(inFile,name);
cout<<name<<endl;
//reading year
getline(inFile,name);
cout<<name<<endl;
// reading data
for(int i=0; i<12; i++){
inFile>>d;
data[i] = d;
}
inFile.close();
return true;
}
// function to find average
float FindAve(float data[]){
float sum =0;
for(int i=0; i<12; i++){
sum = sum+data[i];
}
return sum/12.0;
}
int main(){
float data[12]; // holda company data
// reading data from file
ReadFile(data);
float average = FindAve(data);
cout<<"Average: "<< fixed << setprecision(3)<<average<<endl;
cout<<"Writing average to file"<<endl;
//writing average to outfile 'oakOut.txt'
ofstream outFile;
outFile.open("oakOut.txt");
outFile<<" Average leaves length was calculated to be: "<< fixed << setprecision(3)<<average;
}
/*
Output:
Average leaves length was calculated to be: 32.408
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.