How do I write a C++ class program to convert temperatures from Celsius to Fahrenheit and vice versa?

Dani AI

Generated

— the answers so far are on the right track: gave the basic arithmetic and pointed to searching existing threads. Below is a practical, class-oriented approach that fills gaps not shown in the replies (type safety, testing, API design, and error handling).

enum class Unit { Celsius, Fahrenheit, Kelvin };

class Temperature {
public:
    explicit Temperature(double value, Unit unit) noexcept;
    double value() const noexcept;
    Unit unit() const noexcept;

    Temperature to(Unit target) const noexcept;    // convert and return new Temperature
    static Temperature fromCelsius(double v) noexcept;
    static Temperature fromFahrenheit(double v) noexcept;
    static Temperature fromKelvin(double v) noexcept;

    // optional: arithmetic and streaming operator prototypes
    Temperature operator+(const Temperature& other) const;
    Temperature operator-(const Temperature& other) const;

private:
    double m_value;
    Unit   m_unit;
};

Implementation notes (gaps to watch for in simple examples): store the internal value as double for precision, convert via a single canonical unit (pick one scale internally and map to/from it), and keep conversion math isolated in a small helper so tests can verify it. Make single-arg constructors explicit to avoid accidental implicit conversions. Decide whether invalid physical values (below absolute zero) will throw, clamp, or be represented by an error state.

Testing and robustness: include unit tests that perform round-trip checks (A -> B -> A) with a small epsilon (for example 1e-6), test canonical reference points (freezing/boiling and absolute zero), and validate parsing/IO with locale-aware parsing. Mark trivially evaluable helpers constexpr where possible and use noexcept on functions that cannot fail.

Recommended Answers

All 2 Replies

How do I write a C++ class program to convert temperatures from Celsius to Fahrenheit and vice versa?

Use the Daniweb search engine. There have been scores of threads dealing with this that can help you get started.

I use to make functions, and converters for all my Chem. class stuff.

from F to C: temperature = (temperature - 32.0f) / 1.8f; from K to C: temperature = -273.15f + temperature; edit:
I figure you know basic algebra to go from C to F, F to K, etc.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.