In this article we are going to create a program to perform temperature conversion between the following types.
- celsius to Fahrenheit
- celsius to kelvin
- Fahrenheit to celsius
- kelvin to celsius
- Fahrenhiet to kelvin
- kelvin to Fahrenheit
But before writing the code we should know the formula to perform these operations.
- Celsius to Fahrenheit (0°C × 9/5) + 32) (Multiply the temperature in celsius by 9/5 and then add 32 to that value)
- Celsius to Kelvin (0°C + 273) (Add 273 to the temperature in Celsius)
- Fahrenheit to Celsius ((32°F − 32) × 5/9 = 0°C) (subtract 32 from the temperature in kelvin and multiply it with 5/9)
- Kelvin to Celsius (0K − 273) (subtract 273 from the temperature in kelvin)
- Fahrenheit to kelvin ((32°F − 32) × 5/9 + 273) (Subtract 32 from the temperature tin multiply it with 5/9 and then add 273 to it)
- Kelvin to Fahrenheit ((0K − 273) × 9/5 + 32) (Subtract 273 from the temperature in kelvin, multiply it with 9/5 and then add 32 to it)
Let us get to the coding part. The idea is to create a class which has a method for each of these conversions.
Create a class called Temperature.
Then create methods in class like this for each of the conversions.
This method converts the celsius to Fahrenheit. Round the result to 2 decimal places and return it.
We should create methods like this for other type of conversions as well. The complete code looks like this.
Hope this article is helpful.