Validation in Setters

Lab C++ Intermediate 20 points

Write class Temperature storing Celsius with a setter bool setCelsius(double) that rejects values below -273.15, plus fahrenheit(). For each input print the Fahrenheit value (1 decimal) or invalid.

Input

n, then n numbers.

Output

n lines.

Example

Input

3
100
-300
0

Output

212.0
invalid
32.0
Sample input available Sample output available
Editor
C++

Hints

Return false from the setter instead of storing a bad value.

Solution explanation

Setters guard the class's invariants - an object can never hold an impossible temperature.

Show solution
#include <iostream>
#include <iomanip>
using namespace std;

class Temperature {
public:
    bool setCelsius(double c) {
        if (c < -273.15) return false;
        celsius_ = c;
        return true;
    }
    double fahrenheit() const { return celsius_ * 9 / 5 + 32; }

private:
    double celsius_ = 0;
};

int main() {
    Temperature t;
    int n;
    cin >> n;
    cout << fixed << setprecision(1);
    for (int i = 0; i < n; i++) {
        double c;
        cin >> c;
        if (t.setCelsius(c)) cout << t.fahrenheit() << "\n";
        else cout << "invalid\n";
    }
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD