Sunday, April 14, 2024

Temperature Converter Using Abstraction in C++



 


Program Listing

#include <iostream>

#include <iomanip>



// Abstract class for temperature conversion

class TemperatureConverter {

public:

    virtual void setTemperature(double temp) = 0;

    virtual double toCelsius() = 0;

    virtual double toFahrenheit() = 0;

};


// Concrete class for temperature conversion

class FahrenheitToCelsiusConverter : public TemperatureConverter {

private:

    double temperature;


public:

    void setTemperature(double temp) {

        temperature = temp;

    }


    double toCelsius() {

        return (temperature - 32) * 5.0 / 9.0;

    }


    double toFahrenheit() {

        return temperature;

    }

};


class CelsiusToFahrenheitConverter : public TemperatureConverter {

private:

    double temperature;


public:

    void setTemperature(double temp) {

        temperature = temp;

    }


    double toCelsius() {

        return temperature;

    }


    double toFahrenheit() {

        return (temperature * 9.0 / 5.0) + 32;

    }

};


int main() {

    double temp;

    char choice;


    std::cout << "\n\tTemperature Converter Using Abstraction in C++\n" << std::endl;

    std::cout << "\t[1] Fahrenheit to Celsius" << std::endl;

    std::cout << "\t[2] Celsius to Fahrenheit" << std::endl;

    std::cout << "\n\tEnter your choice: ";

    std::cin >> choice;


    TemperatureConverter* converter = nullptr;


    if (choice == '1') {

        converter = new FahrenheitToCelsiusConverter();

        std::cout << "\n\tEnter temperature in Fahrenheit: ";

    } else if (choice == '2') {

        converter = new CelsiusToFahrenheitConverter();

        std::cout << "\n\tEnter temperature in Celsius: ";

    } else {

        std::cerr << "\tInvalid choice. Exiting." << std::endl;

        return 1;

    }


    std::cin >> temp;

    converter->setTemperature(temp);


    if (choice == '1') {

        std::cout << "\n\tThe Temperature in Celsius: " <<std::fixed <<std::setprecision(2)  << converter->toCelsius() << std::endl;

    } else {

        std::cout << "\n\tThe Temperature in Fahrenheit: " << std::fixed <<std::setprecision(2)  << converter->toFahrenheit() << std::endl;

    }


    delete converter;

   std::cout << "\n\n\tEnd of Program. Thank you for using this program." << std::endl;

    return 0;

}


No comments:

Post a Comment