Skip to content
Exercise · Variables and Types · lesson 6 of 10

Exercise: temperature conversion

Write two functions: double to_fahrenheit(double c) converts a temperature from degrees Celsius to degrees Fahrenheit, and double to_celsius(double f) converts it back. The scales are related by the formulas F = C × 1.8 + 32 and C = (F − 32) × 5/9. The factors kFahrenheitPerCelsius (1.8) and kCelsiusPerFahrenheit (5.0 / 9.0) are already defined in the file.

  • to_fahrenheit(100.0) → 212.0
  • to_fahrenheit(-40.0) → -40.0
  • to_celsius(32.0) → 0.0

Constraints: the temperature is not below absolute zero (−273.15 °C), and the result is compared with the expected value to within 1e-9.

temperature.cpp — cpp
cpp · 11 lines
Ctrl+Enter run · Esc leave editor