Introduction
Temperature conversion between Fahrenheit and Celsius is a common task in many applications. To convert Fahrenheit to Celsius, you can use the following formula:
let celsius = (fahrenheit - 32) * 5/9;
This program will help convert a given temperature from Fahrenheit to Celsius using JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts a temperature in Fahrenheit.
- Converts the temperature to Celsius.
- Returns and displays the result in Celsius.
Example:
Input:
77°F
Output:
25°C
Input:
32°F
Output:
0°C
Solution Steps
- Read the Input Temperature: Provide the temperature in Fahrenheit either by user input or directly within the code.
- Convert Fahrenheit to Celsius: Use the formula
Celsius = (Fahrenheit - 32) * 5/9
. - Display the Result: Print the result in Celsius.
JavaScript Program
// JavaScript Program to Convert Fahrenheit to Celsius
// Author: https://www.javaguides.net/
function convertFahrenheitToCelsius(fahrenheit) {
// Step 1: Apply the conversion formula
let celsius = (fahrenheit - 32) * 5/9;
// Step 2: Return the result
return celsius;
}
// Example input
let fahrenheitTemperature = 77;
let celsiusTemperature = convertFahrenheitToCelsius(fahrenheitTemperature);
console.log(`${fahrenheitTemperature}°F is equal to ${celsiusTemperature.toFixed(2)}°C`);
Output
77°F is equal to 25.00°C
Example with Different Input
let fahrenheitTemperature = 32;
let celsiusTemperature = convertFahrenheitToCelsius(fahrenheitTemperature);
console.log(`${fahrenheitTemperature}°F is equal to ${celsiusTemperature.toFixed(2)}°C`);
Output:
32°F is equal to 0.00°C
Explanation
Step 1: Apply the Conversion Formula
- The formula to convert Fahrenheit to Celsius is: let celsius = (fahrenheit - 32) * 5/9; This formula is used to calculate the Celsius equivalent of the Fahrenheit temperature.
Step 2: Return the Result
- The function returns the result, which is printed using
console.log()
. The result is rounded to two decimal places usingtoFixed(2)
.
Conclusion
This JavaScript program demonstrates how to convert a temperature from Fahrenheit to Celsius using a simple mathematical formula. Temperature conversion is a basic task in many applications, and this solution provides an easy way to handle it in JavaScript.
Comments
Post a Comment
Leave Comment