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

Given the temperature in Celsius, we have change it to Fahrenheit using the class and object approach.
Submitted by Shubh Pachori, on August 13, 2022

Example:

Input:
Enter Temperature in Celsius: 43

Output:
Temperature in Fahrenheit : 109.4

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

#include <iostream>
using namespace std;

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

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

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

    fahrenheit = ((celsius * 9) / 5) + 32;

    // returning converted temperature
    return fahrenheit;
  }
};

int main() {
  // create a object
  CelsiusToFahrenheit 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.CToF();

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

  return 0;
}

Output:

Enter Temperature in Celsius: 98
Temperature in Fahrenheit : 208.4

Explanation:

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

In the main() function, we are creating an object C of class CelsiusToFahrenheit, reading the temperature by the user using the function getTemperature(), and finally calling the CToF() member function to convert the given temperature from Celsius to Fahrenheit. The CToF() function contains the logic to convert the given temperature from celsius 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.