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