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

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

Example:

Input:
Enter Temperature in Kelvin: 321

Output:
Temperature in Fahrenheit : 118.13

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

#include <iostream>
using namespace std;

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

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

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

    fahrenheit = (9.0 / 5) * (kelvin - 273.15) + 32;

    // returning converted temperature
    return fahrenheit;
  }
};

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

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

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

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

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

  return 0;
}

Output:

Enter Temperature in Kelvin: 300
Temperature in Fahrenheit : 80.33

Explanation:

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

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

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





Comments and Discussions!

Load comments ↻






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