Simvik

Temperature conversion with rounding

Convert tenths of a degree Celsius to Fahrenheit and round correctly below zero. A medium embedded C problem (Fixed-point and signal processing), run and…

medium · Fixed-point and signal processing · rounding · negative-numbers

Temperatures are stored in tenths of a degree as integers. Convert c_tenths from Celsius to Fahrenheit, also in tenths: F = C * 9 / 5 + 32, so in tenths the offset is 320.

Round the result to the nearest tenth. That includes negative values: -1.8 must become -2, not -1.

Starter code

int16_t c_to_f_tenths(int16_t c_tenths) {
  // Integer division truncates toward zero, which rounds negative results the wrong way.
  return (int16_t)(c_tenths * 9 / 5 + 320);
}

Example tests

Room temperature

printf("%d\n", c_to_f_tenths(250));

Expected output:

770

Minus forty is the same on both scales

printf("%d\n", c_to_f_tenths(-400));

Expected output:

-400

Learn it first

More Fixed-point and signal processing problems