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.
#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;
}
Comments
Leave a comment