C++ examples for Class:Class Creation
Create class to get the Gas Mileage
#include <iostream> /*from w w w. j ava 2 s . co m*/ class Car { private: double milesDriven = 0.0f; double gallonsUsed = 0.0f; double tripMPG = 0.0f; double totalMPG = 0.0f; public: Car(); // SETTERS void setMilesDriven(); void setGallonsUsed(); void setTripMPG(); void setTotalMPG(); // GETTERS double getMilesDriven(); double getGallonsUsed(); double getTripMPG(); double getTotalMPG(); void run(); }; Car::Car() {} // SETTERS void Car::setMilesDriven() { milesDriven = 0.0f; std::cout << "Enter miles driven (-1 to quit): "; std::cin >> milesDriven; } void Car::setGallonsUsed() { gallonsUsed = 0.0f; std::cout << "Enter gallons used: "; std::cin >> gallonsUsed; } void Car::setTripMPG() { tripMPG = 0.0f; tripMPG = (getMilesDriven() / getGallonsUsed()); } void Car::setTotalMPG() { totalMPG += getTripMPG(); } // GETTERS double Car::getMilesDriven() { return milesDriven; } double Car::getGallonsUsed() { return gallonsUsed; } double Car::getTripMPG() { return tripMPG; } double Car::getTotalMPG() { return totalMPG; } void Car::run() { setMilesDriven(); if (getMilesDriven() != -1) { setGallonsUsed(); setTripMPG(); setTotalMPG(); std::cout << "MPG this trip: " << getTripMPG() << std::endl; std::cout << "Total MPG: " << getTotalMPG() << std::endl; } } int main(int argc, const char *argv[]) { Car gm; while (gm.getMilesDriven() != -1) { gm.run(); } return 0; }