Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 66 / 68

Converting temperatures (Celsius and Fahrenheit)

This lesson covers converting between Celsius and Fahrenheit in Objective-C, as practice at turning a formula into code.

Celsius to Fahrenheit is "ยฐC ร— 9/5 + 32"; Fahrenheit to Celsius is "(ยฐF โˆ’ 32) ร— 5/9". Unit conversion is a classic programming exercise.

The sample code provides celsiusToFahrenheit() and fahrenheitToCelsius(), each following its formula. You can watch 25 degrees Celsius become 77 Fahrenheit and 77 Fahrenheit become 25 Celsius.

A common early stumble is the order of operations. Get the sequence of multiplication, division, and addition wrong in c * 9 / 5 + 32 and the answer is wrong, so it pays to understand the formula before writing it.

It is good practice at turning a plain formula straight into code. Special values such as absolute zero (โˆ’273.15ยฐC) go through the same formula unchanged.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)