Answer to Question #315152 in C++ for khan

Question #315152

Implement a structure, Car. The structure has the following data member:

1. int petrolLevel – that indicates the liters of petrol in the car’s petrol tank. PetrolLevel for

this car can only be in the range 0 – 45 liters.

The structure has the following member functions:

1. void setPetrolLevel(int petrolLevelVal) – a setter for petrol level, cannot set value greater

than 45.

2. int getPetrolLevel() – a getter for petrolLevel

3. Car() – a default constructor

4. Car(int petrolLevelVal) – a parametrized constructor

5. bool MoveCar(int distanceKM) – a function that takes an integer as an argument and

moves the car to the argument value which is in Km. Provided the petrol tank has enough

fuel. Successful movement of the car returns true otherwise returns false. Moving for

each km causes the petrolLevel to go low by one.

6. void Refill() – a function that refills the car tank to the maximum value of petrolLevel

7. bool isEmpty() – a function that tells whether the Petrol tank is Empty or not


1
Expert's answer
2022-03-21T12:35:59-0400
struct Car {
    int petrolLevel;
    
    void setPetrolLevel(int petrolLevelVal);
    int getPetrolLevel();
    Car();
    Car(int petrolLevelVal);
    bool MoveCar(int distanceKM);
    void Refill();
    bool isEmpty();
};


void Car::setPetrolLevel(int petrolLevelVal) {
    if (petrolLevelVal < 0) {
        return;
    }
    petrolLevel += petrolLevelVal;
    if (petrolLevel > 45) {
        petrolLevel = 45;
    }
}


int Car::getPetrolLevel() {
    return petrolLevel;
}


Car::Car() {
    petrolLevel = 0;
}


Car::Car(int petrolLevelVal) {
    setPetrolLevel(petrolLevelVal);
};
bool Car::MoveCar(int distanceKM) {
    const double L_PER_100KM = 12;
    double consumption = L_PER_100KM * distanceKM / 100.0;


    if (consumption > petrolLevel) {
        petrolLevel = 0;
        return false;
    }
    petrolLevel -= static_cast<int>(consumption);
    return true;
}


void Car::Refill() {
    petrolLevel = 45;
}


bool Car::isEmpty() {
    return petrolLevel == 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