Temperature Conversions

Temperature Conversions

Define a Temperature class with a private member variable celsius. Add static methods to convert Celsius to Fahrenheit and Fahrenheit to Celsius. Demonstrate the use of these static methods without creating an instance of Temperature.

Hint

(°C × 9/5) + 32 = °F

Add the following static methods:

Answer

#include <iostream>

class Temperature {
public:
    double celsius;

    // Constructor to initialize the celsius member variable
    Temperature(double temp_celsius) : celsius(temp_celsius) {}

    // Static method to convert Celsius to Fahrenheit
    static double celsius_to_fahrenheit(double celsius) {
        return (celsius * 9.0 / 5.0) + 32.0;
    }

    // Static method to convert Fahrenheit to Celsius
    static double fahrenheit_to_celsius(double fahrenheit) {
        return (fahrenheit - 32.0) * 5.0 / 9.0;
    }
};

int main() {
    // Demonstrate the use of static methods without creating an instance of Temperature
    double temp_celsius = 25.0;
    double temp_fahrenheit = Temperature::celsius_to_fahrenheit(temp_celsius);
    std::cout << temp_celsius << " degrees Celsius is " << temp_fahrenheit << " degrees Fahrenheit." << std::endl;

    temp_fahrenheit = 77.0;
    temp_celsius = Temperature::fahrenheit_to_celsius(temp_fahrenheit);
    std::cout << temp_fahrenheit << " degrees Fahrenheit is " << temp_celsius << " degrees Celsius." << std::endl;

    return 0;
}
Questions