Convert Celsius to Fahrenheit
Learn how to solve the freeCodeCamp algorithm 'Convert Celsius to Fahrenheit' using the standard JavaScript mathematical operations.
Let's take a look at the freeCodeCamp algorithm 'Convert Celsius to Fahrenheit'.
In this algorithm, we're passing an argument celsius
into our convertToF()
function. Within the function, we need to come up with the logic for the fahrenheit
variable to correctly convert Celsius into Fahrenheit.
We know that in order to convert Celsius to Fahrenheit, we need to take the temperature in Celsius and multiply it by 9/5
, then add 32
.
Requirements
convertToF(0)
should return a numberconvertToF(-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
Psuedocode
Let's take break down what we need to do in order to solve this algorithm. We need to take any given temperature in Celsius. Then we need to take that Celsius temperature and then divide it by 9/5. Afterwards, we take the product and then add 32. Lastly, we return the Fahrenheit value.
Here's a look at how we can pseudocode this:
// take temperature in celsius
// multiply celsius by (9/5) and add 32
// return fahrenheit
Breaking Down the Algorithm
Let's convert our psuedocode into actual code that the computer will understand.
Create the Function and Argument
First let's create the convertToF()
function. Within that function, we will pass in the argument celsius
.
function convertToF(celsius) {
}
Create the Logic
From here, we need to create the actual logic that will take the celsius
input, then place it within our function.
var fahrenheit = celsius * (9/5) + 32;
Return The Result
Lastly, we just need to return the result which is stored in the fahrenheit
variable.
return fahrenheit;
Solution
Here we can put all the pieces of the function together, then we can call it by passing in a value of 30 to test it out. If all goes well, our Celsius to Fahrenheit converter should return 86.
function convertToF(celsius) {
var fahrenheit = celsius * (9/5) + 32;
return fahrenheit;
}
convertToF(30);
// Call the function, passing an input of 30
// Expected output: 86
## Recap Hopefully this was a helpful walkthrough of the [freeCodeCamp algorithm](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/convert-celsius-to-fahrenheit/?utm_source=codesnippet.io) on how to convert celsius to fahrenheit!
Shoot me an email at [email protected]
with any questions and if you enjoyed this, subscribe below! 👇
Help us improve our content