C++ program to convert the temperature from Kelvin to Celsius using class

Given temperature in Kelvin, we have change it to Celsius using the class and object approach.
Submitted by Shubh Pachori, on September 05, 2022

Example:

Input:
Enter Temperature in Kelvin: 300

Output:
Temperature in Celsius : 26.85

C++ code to convert the temperature from Kelvin to Celsius using the class and object approach

#include <iostream>
using namespace std;

// create a class
class KelvinToCelsius {
  // private data member
 private:
  float kelvin;

  // public functions
 public:
  // getTemperature() function to 
  // get the Temperature
  void getTemperature() {
    cout << "Enter Temperature in Kelvin: ";
    cin >> kelvin;
  }

  // KToC() function to convert the temperature
  double KToC() {
    // initialising float type variables 
    // to perform operations
    float celsius;

    celsius = kelvin - 273.15;

    // returning the converted temperature
    return celsius;
  }
};

int main() {
  // create a object
  KelvinToCelsius K;

  // float type variable to store 
  // the converted temperature
  float temperature;

  // function is called by the object 
  // to store the temperature
  K.getTemperature();

  // KToC() function to convert 
  // the temperature
  temperature = K.KToC();

  cout << "Temperature in Celsius: " << temperature;

  return 0;
}

Output:

Enter Temperature in Kelvin: 285.23
Temperature in Celsius: 12.08

Explanation:

In the above code, we have created a class KelvinToCelsius, one float type data member kelvin to store the temperature in kelvin, and public member functions getTemperature() and KToC() to store and convert the given temperature.

In the main() function, we are creating an object K of class KelvinToCelsius, reading the temperature by the user using the function getTemperature(), and finally calling the KToC() member function to convert the given temperature from kelvin to celsius. The KToC() function contains the logic to convert the given temperature from kelvin to celsius and printing the result.

C++ Class and Object Programs (Set 2) »





Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.