This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, March 14, 2023

Write a C++ program that will ask for a temperature in Fahrenheit and display it in Celsius using class named temp and member functions

 here's an example program that converts temperature from Fahrenheit to Celsius using a class named Temp and member functions:

#include <iostream>
using namespace std;

class Temp {
private:
    float fahrenheit;

public:
    void getTemp() {
        cout << "Enter temperature in Fahrenheit: ";
        cin >> fahrenheit;
    }

    void convertToFahrenheit() {
        cout << fahrenheit << " degrees Fahrenheit is " << (fahrenheit - 32) * 5/9 << " degrees Celsius." << endl;
    }
};

int main() {
    Temp temp;
    temp.getTemp();
    temp.convertToFahrenheit();
    return 0;
}

Explanation:

  • We define a class named Temp with a private data member fahrenheit and two member functions: getTemp() and convertToFahrenheit().
  • The getTemp() function prompts the user to enter the temperature in Fahrenheit and stores it in the fahrenheit data member.
  • The convertToFahrenheit() function converts the temperature from Fahrenheit to Celsius using the formula (fahrenheit - 32) * 5/9 and displays the result on the screen.
  • In main(), we create an object of class Temp, call the getTemp() function to get the temperature in Fahrenheit from the user, and then call the convertToFahrenheit() function to display the temperature in Celsius.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget