In: Computer Science
1. Writing a Random Temperature File
Write a function that writes a series of random Fahrenheit
temperatures and their correspond- ing Celsius temperatures to a
tab-delimited file. Use 32 to 212 as your temperature range. From
the user, obtain the following:
• The number of temperatures to randomly generate.• The name of the output file.
A sample run is included below (you must follow the format provided below):
Please enter the name of your file: Example.txt Please enter the number of iterations: 100
Example.txt: Fahrenheit Celsius 152.00 66.67 97.00 36.11 32.00 0.00 99.00 37.22 35.00 1.67 etc...
2. Reading a Random Temperature File
Write a function that reads a file produced by Problem 2. Focusing
only on the Celsius temperatures in the file, calculate and display
to screen the following:
• Mean or Average• Minimum
• Maximum
please include eveery detail you can. plus comments. Thank you !
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
void write_to_file(string &filename, int count){
ofstream outfile(filename.c_str());
if(outfile.is_open()){
outfile<<"Fahrenheit\tCelsius\n";
double fahrenheit,celsius;
for(int i=1; i<=count; i++){
fahrenheit= 32 + rand()%181;
celsius = (fahrenheit-32)/1.8;
outfile<<fixed<<setprecision(2)<<fahrenheit<<"\t"<<fixed<<setprecision(2)<<celsius<<endl;
}
outfile.close();
}else{
cout<<"Unable to write data to file."<<endl;
exit(EXIT_FAILURE);
}
}
void read_from_file(string &filename, double &mean, double &min, double &max){
ifstream infile(filename.c_str());
int count=0;
double fahrenheit,celsius;
double total_celsius;
if(infile.is_open()){
string header;
getline(infile,header,'\n');
while(infile>>fahrenheit>>celsius){
total_celsius+=celsius;
count+=1;
if(count==1){
min=max=celsius;
}
if(min>celsius)min=celsius;
if(max<celsius) max=celsius;
}
mean = total_celsius/count;
infile.close();
}else{
cout<<"Unable to write data to file."<<endl;
exit(EXIT_FAILURE);
}
}
int main(){
string filename;
int iterations;
cout<<"Please enter the name of your file: "; cin>>filename;
cout<<"Please enter the number of iterations: ";cin>>iterations;
write_to_file(filename,iterations);
double mean=0, min_temp, max_temp;
read_from_file(filename,mean,min_temp,max_temp);
cout<<"Mean temperature : "<<mean<<" C"<<endl;
cout<<"Min temperature : "<<fixed<<setprecision(2)<<min_temp<<" C"<<endl;
cout<<"Max temperature : "<<fixed<<setprecision(2)<<max_temp<<" C"<<endl;
}