(Second part)
The report.txt file that your program produces should contain all of the original data, but
at the end of each line, it should show the average speed of the car, in miles per hour, on
that part of the trip. The three numbers on each line should be separated by spaces.
Format the numbers so that they all show exactly 1 decimal place. For the above
vacation.txt file, the corresponding report.txt file should look approximately like this:
5.3 5.5 57.8
12.0 10.5 68.6
52.5 61.0 51.6
Overall average speed: 54.4
Note that all of the numbers are displayed with one decimal place.
Write a FindAverage function that takes the distance in miles and time in minutes
and returns in the function name the average speed in miles per hour. Call this
function each time you need to compute an average speed.
By overall average speed, we mean the total distance (in miles) divided by the total
time (in hours). All of the answers, then, are in miles per hour.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
//a FindAverage function that takes the distance in miles and time in minutes
//and returns in the function name the average speed in miles per hour.
float FindAverage(float numberMiles,float time){
return numberMiles/(time/60.0);
}
int main()
{
ifstream ifstreamVacation;
ofstream ofstreamReport;
float numberMiles;
float time;
float totalDistance=0;
float totalTime=0;
ifstreamVacation.open("vacation.txt");
ofstreamReport.open("report.txt");
if(ifstreamVacation.is_open() && ifstreamVacation.is_open()){
while(ifstreamVacation>>numberMiles>>time){
float averageSpeed=FindAverage(numberMiles,time);
totalDistance+=numberMiles;
totalTime+=(time/60.0);
ofstreamReport<<fixed<<setprecision(1)<<numberMiles<<" "<<setprecision(1)<< time<<" "<<setprecision(1)<<averageSpeed<< endl;
}
}
//By overall average speed, we mean the total distance (in miles) divided by the total
//time (in hours). All of the answers, then, are in miles per hour.
float overallAverageSpeed=totalDistance/totalTime;
ofstreamReport<<"Overall average speed: "<<fixed<<setprecision(1)<<overallAverageSpeed;
ifstreamVacation.close();
ifstreamVacation.close();
system("pause");
return 0;
}
Comments
Leave a comment