Saturday, May 25, 2024

Temperature Converter in C++ Using Object-Oriented Programming

 




#include <iostream>

#include <iomanip>


class TemperatureConverter {

public:

    // Constructor

    TemperatureConverter() {}


    // Convert Celsius to Fahrenheit

    double celsiusToFahrenheit(double celsius) {

        return (celsius * 9.0 / 5.0) + 32;

    }


    // Convert Fahrenheit to Celsius

    double fahrenheitToCelsius(double fahrenheit) {

        return (fahrenheit - 32) * 5.0 / 9.0;

    }

};


int main() {

    TemperatureConverter converter;

    char choice;


    do {

        std::cout << "\n\n\tTemperature Converter Main Menu\n" << std::endl;

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

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

        std::cout << "\t[3] Quit Program" << std::endl;

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

        std::cin >> choice;


        if (choice == '1') {

            double celsius;

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

            std::cin >> celsius;

            double fahrenheit = converter.celsiusToFahrenheit(celsius);

            std::cout << "\tTemperature in Fahrenheit: " <<std::fixed <<std::setprecision(2)<< fahrenheit << std::endl;

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

            double fahrenheit;

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

            std::cin >> fahrenheit;

            double celsius = converter.fahrenheitToCelsius(fahrenheit);

            std::cout << "\tTemperature in Celsius: " <<std::fixed <<std::setprecision(2)<<  celsius << std::endl;

        } else if (choice != '3') {

            std::cout << "\n\tInvalid choice. Please try again." << std::endl;

        }


    } while (choice != '3');

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

    return 0;

}


No comments:

Post a Comment