You are living off-campus and drive your car to ODU campus everyday of a week. You wonder how many mileages you travel in a week (just to campus and back home) and how much you need to pay for the gas. You log your travel mileage every day during a week (just to campus and back home). This information has been saved in an input file called “mileage.txt”.
Design an algorithm and write a C++ program to do the following:
Algorithm:
The program:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
const double MPG=35;
const int N=7;
double mileage[N];
char fin_name[] = "mileage.txt";
char fout_name[] = "cost.txt";
ifstream fin(fin_name);
if (!fin) {
cerr << "Can\'t open file \"" << fin_name << "\"\n";
exit(1);
}
for (int i=0; i<N; i++) {
fin >> mileage[i];
cout << "Mileage for the day " << i+1 << " is "
<< mileage[i] << endl;
}
fin.close();
double price;
cout << endl << "Enter the price for one-gallon gas: ";
cin >> price;
double tot_mileage=0.0;
for (int i=0; i<N; i++) {
tot_mileage += mileage[i];
}
double gallons = tot_mileage / MPG;
double cost = gallons * price;
cout << "Total cost of travel in the week is $"
<< fixed << setprecision(2) << cost << endl;
ofstream fout(fout_name);
if (!fout) {
cerr << "Erorr opening file \"" << fout_name << "\"\n";
exit(1);
}
fout << fixed << setprecision(2) << cost << endl;
fout.close();
return 0;
}
Comments
Leave a comment