Define a class called Odometer that will be used to track fuel and mileage for a vehicle.

LANGUAGE:  C++

CHALLENGE:

Define a class called Odometer that will be used to track fuel and mileage for a vehicle.

  • Include member variables to track the distance driven (in miles) and the fuel efficiency of the vehicle (in miles per gallon).
  • The class will have a constructor that accepts one parameter and initializes distance to 0 and fuel efficiency to the value of its parameter.
  • Include a member function to reset the odometer to 0 miles, a member function that accepts the miles driven for a trip and adds it to the odometer’s total, and a member function that returns the number of gallons of gasoline that the vehicle has consumed since the odometer was last reset.

Use your Odometer class in a program that would ask the user to input fuel efficiency and then create an Odometer object using your constructor to initialize the member variables to their appropriate values.

Then the program would ask the user to input the miles driven for two trips and output the gallons of gas the vehicle consumed on these two trips.
Then it will reset the odometer and repeat the procedure for two more trips.

SOLUTION:


class Odometer{
    private:
        float dist;
        float fuel_eff;
    public:
        Odometer(float a){
            dist = 0;
            fuel_eff = a;
        }
      
        void resetOdometer(){
            dist = 0;
        }
      
        void addMilesToOdometer(float x){
            dist = dist + x;
        }
      
        float gallonConsumed(){
            return(dist/fuel_eff);
        }     
};

int main(){
    float fuel_efficiency;
    float distance1, distance2;
    cout<<"Your fuel efficiency in miles per gallon: Enter"<<endl; cin>>fuel_efficiency;
  
    Odometer obj(fuel_efficiency);
  
    cout<<"Your first trip distance in miles: Enter"<<endl; cin>>distance1;
    obj.addMilesToOdometer(distance1);
  
    cout<<"Your second trip distance in miles: Enter"<<endl; cin>>distance2;
    obj.addMilesToOdometer(distance2);
  
    cout<<"The vehicle consumed "<<obj.gallonConsumed()<<" gallon(s)"<<endl;
  
    obj.resetOdometer();
  
    cout<<"Your third trip distance in miles: Enter"<<endl; cin>>distance1;
    obj.addMilesToOdometer(distance1);
  
    cout<<"Your fourth trip distance in miles: Enter"<<endl; cin>>distance2;
    obj.addMilesToOdometer(distance2);
  
    cout<<"The vehicle consumed "<<obj.gallonConsumed()<<" gallon(s)"<<endl;  
}