10. Temperature Unit Conversion

#include <iostream>
using namespace std;
 
// Default: convert raw reading to Celsius
float readTemp(int raw) {
    return raw / 10.0f;
}
 
// Overloaded: convert to Celsius or Fahrenheit
float readTemp(int raw, char unit) {
    float celsius = raw / 10.0f;
    if (unit == 'F') {
        return celsius * 1.8f + 32.0f;
    }
    return celsius; // 'C'
}
 
int main() {
    int raw;
    char unit;
    cin >> raw >> unit;
 
    if (unit == 'D') {
        cout << readTemp(raw);
    } else {
        cout << readTemp(raw, unit);
    }
 
    return 0;
}

Explanation & Logic Summary:

  • Overloading creates multiple readTemp interfaces:
    • Default conversion to °C
    • Unit-selectable conversion
  • The compiler chooses the correct overload based on the number of parameters.
  • Celsius is derived from raw sensor value by division.
  • Fahrenheit uses the standard conversion formula.

Firmware Relevance & Real-World Context:

  • Sensors often provide readings in different units depending on firmware needs (local processing vs UI/cloud).
  • Overloading keeps APIs clean:
    • readTemp() for typical control-loop usage
    • readTemp(raw, unit) for UI/export formatting
  • This mirrors real sensor driver design in embedded systems and HAL layers.

 

 

 


 

Loading...

Input

250 D

Expected Output

25