Gum Gum - 9 months ago 22
C++ Question

Creating a Class to convert Centigrade to Fahrenheit and vice versa

I've recently started programming in C++ in one of my high school classes. I'm currently learning about Classes and I'm having some trouble creating a class that will convert from Centigrade to Fahrenheit and Fahrenheit to Centigrade. I feel like I'm totally doing this wrong. Any help would be great. The program runs fine but doesn't convert, how do I go about grabbing the 'dCent' and 'dFahr'and using it inside my Convert class?

#include <iostream>
using namespace std;

int main() {
int nUserInput;
double dCent, dFahr;
cout << "Do you want to convert from Centigrade to Fahrenheit [1] or from Fahrenheit to Centigrade [2]" <<endl;
cin >> nUserInput;

if (nUserInput == 1) {
cout << "Enter the Centigrade" <<endl;
cin >> dCent;
} else if (nUserInput == 2) {
cout << "Enter the Fahrenheit" <<endl;
cin >> dFahr;
}

Convert tempConverter;
tempConverter.
}


class Convert {
public:
void centToFahr() {
//dCent = dCent * 9 / 5 + 32;
}
void fahrToCent() {
//dCent = (dFahr - 32) * 5 / 9;
}
};

Answer Source

Try this :

    class Convert {
public:
    double centToFahr(double dCent) {
        return dCent * 9 / 5 + 32;
    }
    double fahrToCent(double dFahr) {
        return (dFahr - 32) * 5 / 9;
    }
};

int main() {
    int nUserInput;
    double dCent, dFahr;
    Convert tempConverter;
    cout << "Do you want to convert from Centigrade to Fahrenheit [1] or from Fahrenheit to Centigrade [2]" << endl;
    cin >> nUserInput;

    if (nUserInput == 1) {
        cout << "Enter the Centigrade" << endl;
        cin >> dCent;
        cout << "dFahr = " << tempConverter.centToFahr(dCent);
    }
    else if (nUserInput == 2) {
        cout << "Enter the Fahrenheit" << endl;
        cin >> dFahr;
        cout << "dCent = " << tempConverter.fahrToCent(dFahr);
    }
}