Answer to Question #294625 in C++ for Apple

Question #294625

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:

  • Output the mileage for each day.
  • Prompt user to enter the price for one-gallon gas.
  • Calculate and output the total cost of your travel in the week. Your car's Miles per Gallon (MPG) is 35.
  • Save the output in a file named “cost.txt”.
1
Expert's answer
2022-02-07T05:10:32-0500

Algorithm:

  1. Create an array mileage of size 7
  2. Open file "mileage.txt"
  3. Read data into the array
  4. Set total_mileage equal 0
  5. Add all elements of the array mileage to total_mileage
  6. Ask a value of gas cost
  7. Calculate the gas mileage
  8. Calculate the cost
  9. Output the cost
  10. Save the cost into a file


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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog