AlgoMaster Logo

Temperature Converter

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

The conversion direction depends on the scale argument, so the function handles both cases.

Celsius and Fahrenheit measure the same quantity but disagree on two things: where zero sits and how big one degree is. Water freezes at 0 Celsius but 32 Fahrenheit, which gives the offset. Fahrenheit spans 180 degrees between freezing and boiling while Celsius uses only 100, which gives the 9 to 5 ratio between degree sizes. Those two facts make each direction a single formula.

Key Constraints:

  • scale is either "C" or "F" → You only have two branches to handle. Compare the string against "C" to decide which formula to apply, and treat everything else as "F".
  • temp is a real number → The input can be fractional and negative, like 98.6 or -40. Use floating-point arithmetic and divide as a double or float, not as an integer, or you will lose the decimal part.
  • Round to 2 decimal places → The final answer must be rounded to two decimals, so a value like 37.0 is reported as 37.00.

Approach 1: Apply the Conversion Formula

Intuition

The two facts become the Celsius to Fahrenheit formula: multiply by 9/5 to resize the degrees, then add 32 to align the starting points.

F = temp * 9 / 5 + 32

Going the other way reverses both steps in the opposite order. Subtract 32 to undo the offset, then multiply by 5/9 to undo the scaling.

C = (temp - 32) * 5 / 9

The two formulas are mirror images. One scales then shifts, the other shifts then scales back, using the reciprocal ratio.

Algorithm

  1. Check the value of scale.
  2. If scale is "C", the input is Celsius, so compute temp * 9 / 5 + 32.
  3. Otherwise the input is Fahrenheit, so compute (temp - 32) * 5 / 9.
  4. Round the computed value to 2 decimal places and return it.

Example Walkthrough

Input:

100
temp
0
C
scale

Since scale is "C", we apply the Celsius to Fahrenheit formula. First scale the degrees: 100 * 9 / 5 = 180. Then add the offset: 180 + 32 = 212. Rounded to two decimals, the result is 212.00.

212
output

Code