Answer to Question #243757 in C++ for Jay

Question #243757

a. Declare a single structure data type suitable for a car structure of the type illustrated:


Car Number

Miles Driven

Gallons Used

25 1450 62

36 3240 136

44 1792 76

52 2369 105

68 2114 67

 

b. Using the data type declared for Exercise 2a, write a C++ program that inter-actively accepts the above data into an array of five structures. Once the data have been entered, the program should create a report listing each car number and a miles per gallon achieved by the car. At the end of the report include the average miles per gallon achieved by the complete fleet of cars.

 

1
Expert's answer
2021-09-28T11:42:43-0400
#include <iostream>

using namespace std;

struct Car {
    int carNumber = 0;
    int milesDriven = 0;
    int gallonsUsed = 0;
};

int main()
{
    int size = 5;
    Car cars[size];
    for (int i = 0; i < size; i++) {
        cout << "Car " << i + 1 << endl;
        cout << "Car number: ";
        cin >> cars[i].carNumber;
        cout << "Miles driven: ";
        cin >> cars[i].milesDriven;
        cout << "Gallons used: ";
        cin >> cars[i].gallonsUsed;
        cout << endl;
    }

    int totalMiles = 0;
    int totalGallons = 0;
    for (int i = 0; i < size; i++) {
        cout << "Car " << i + 1;
        cout << ", Car number: " << cars[i].carNumber;
        double milesByGallon = (double) cars[i].milesDriven / cars[i].gallonsUsed;
        cout << ", Miles by gallon: " << milesByGallon << endl;
        totalMiles += cars[i].milesDriven;
        totalGallons += cars[i].gallonsUsed;
    }
    double milesByGallon = (double) totalMiles / totalGallons;
    cout << "Average miles per gallon: " << milesByGallon << endl;

    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
APPROVED BY CLIENTS