Convert Celsius to Fahrenheit in JavaScript
Converting a temperature from Celsius to Fahrenheit is a common calculation. It’s a good place to start when learning about algorithms because there are very clear cut steps to converting from Celsius to Fahrenheit.
Algorithm instructions
The algorithm to convert from Celsius to Fahrenheit is the temperature in Celsius times
9/5
, plus32
.You are given a variable
celsius
representing a temperature in Celsius. Use the variablefahrenheit
already defined and assign it the Fahrenheit temperature equivalent to the given Celsius temperature. Use the algorithm mentioned above to help convert the Celsius temperature to Fahrenheit.Don’t worry too much about the function and return statements as they will be covered in future challenges. For now, only use operators that you have already learned.
Provided Test Cases
convertToF(0)
should return a number.convertToF(-30)
should return a value of-22
.convertToF(-10)
should return a value of14
.convertToF(0)
should return a value of32
.convertToF(20)
should return a value of68
.convertToF(30)
should return a value of86
.
Solution #1: multiplication and addition
PEDAC
Understanding the Problem: Our input here is a Celsius temperature, and our output is a Fahrenheit temperature. In other words, the algorithms takes a Celsius temperature and returns a Fahrenheit temperature. Based on the instructions and test cases, it looks like we’re being given whole numbers, but they can be negative. We are given the formula needed to convert Celsius to Fahrenheit, so we don’t need to worry about figuring out the mathematical operations behind the conversion.
Examples/Test Cases: freeCodeCamp has provided us with several test cases above. Our inputs and outputs are both whole numbers and either can be negative.
Data Structure: We aren’t going to have to worry too much about this part of PEDAC for this algorithm. We’re just returning a number.
Algorithm: The steps to convert from Celsius to Fahrenheit are as follows:
- Multiply Celsius value by 9/5
- Add 32 to Celsius value
Code: See below!
Luckily for us, the good people at freeCodeCamp have given us the formula to convert a temperature from celsius to Fahrenheit: you multiply the celsius value by 9/5 then add 32.
The instructions tell us to use the fahrenheit
variable we’re given, but we can refactor this to make it a little, simpler, though. We are declaring the variable fahrenheit
and making it equal to the answer, then just returning it on the next line. fahrenheit
is a local variable that might make it easier for us to understand what the algorithm is doing, but it isn’t really necessary for the algorithm to run. We can get rid of it and just return the answer directly.
If you have other solutions and/or suggestions, please share in the comments!