Home »
C++ Programs
C++ program to convert the temperature from Fahrenheit to Celsius using class
Submitted by Shubh Pachori, on August 14, 2022
Problem statement
Given the temperature in Fahrenheit, we have to change it to Celsius using the class and object approach.
Example:
Input:
Enter Temperature in Fahrenheit: 109.4
Output:
Temperature in Celsius : 43
C++ code to convert the temperature from Fahrenheit to Celsius using class and object approach
#include <iostream>
using namespace std;
// create a class
class FahrenheitToCelsius {
// private data member
private:
float fahrenheit;
// public functions
public:
// getTemperature() function to get the Temperature
void getTemperature() {
cout << "Enter Temperature in Fahrenheit:";
cin >> fahrenheit;
}
// FToC() function to convert the temperature
double FToC() {
// initialising float type variables to perform operations
float celsius;
celsius = (fahrenheit - 32) * 5 / 9;
// returning the converted temperature
return celsius;
}
};
int main() {
// create a object
FahrenheitToCelsius F;
// float type variable to store the converted temperature
float temperature;
// function is called by the object to store the temperature
F.getTemperature();
// FToC() function to convert the temperature
temperature = F.FToC();
cout << "Temperature in Celsius :" << temperature;
return 0;
}
Output
Enter Temperature in Fahrenheit:208.4
Temperature in Celsius:98
Explanation
In the above code, we have created a class FahrenheitToCelsius, one float type data member fahrenheit to store the temperature in fahrenheit, and public member functions getTemperature() and FToC() to store and convert the given temperature.
In the main() function, we are creating an object F of class FahrenheitToCelsius, reading the temperature by the user using function getTemperature() , and finally calling the FToC() member function to convert the given temperature from Fahrenheit to Celsius. The FToC() function contains the logic to convert the given temperature from Fahrenheit to Celsius and printing the result.
C++ Class and Object Programs (Set 2) »