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

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

Example:

Input:
Enter Temperature in Celsius: 45

Output:
Temperature in Kelvin : 318.15

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

#include <iostream>
using namespace std;

// create a class
class CelsiusToKelvin {
  // private data member
 private:
  float celsius;

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

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

    kelvin = celsius + 273.15;

    // returning converted temperature
    return kelvin;
  }
};

int main() {
  // create a object
  CelsiusToKelvin C;

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

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

  // CToF() function to convert the temperature
  temperature = C.CToK();

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

  return 0;
}

Output:

Enter Temperature in Celsius: 23
Temperature in Kelvin : 296.15

Explanation:

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

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

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





Comments and Discussions!

Load comments ↻






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