Introduction
Temperature conversion is a common task in programming. One of the most common conversions is from Celsius to Fahrenheit. The formula to convert Celsius to Fahrenheit is:
let fahrenheit = (celsius * 9/5) + 32;
This program helps convert a given temperature in Celsius to Fahrenheit using JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts a temperature in Celsius.
- Converts the temperature to Fahrenheit.
- Returns and displays the result in Fahrenheit.
Example:
Input:
25°C
Output:
77°F
Input:
0°C
Output:
32°F
Solution Steps
- Read the Input Temperature: Provide the temperature in Celsius either by user input or directly within the code.
- Convert Celsius to Fahrenheit: Use the formula
Fahrenheit = (Celsius * 9/5) + 32
. - Display the Result: Print the result in Fahrenheit.
JavaScript Program
// JavaScript Program to Convert Celsius to Fahrenheit
// Author: https://www.javaguides.net/
function convertCelsiusToFahrenheit(celsius) {
// Step 1: Apply the conversion formula
let fahrenheit = (celsius * 9/5) + 32;
// Step 2: Return the result
return fahrenheit;
}
// Example input
let celsiusTemperature = 25;
let fahrenheitTemperature = convertCelsiusToFahrenheit(celsiusTemperature);
console.log(`${celsiusTemperature}°C is equal to ${fahrenheitTemperature}°F`);
Output
25°C is equal to 77°F
Example with Different Input
let celsiusTemperature = 0;
let fahrenheitTemperature = convertCelsiusToFahrenheit(celsiusTemperature);
console.log(`${celsiusTemperature}°C is equal to ${fahrenheitTemperature}°F`);
Output:
0°C is equal to 32°F
Explanation
Step 1: Apply the Conversion Formula
- The formula to convert Celsius to Fahrenheit is used: (celsius * 9/5) + 32; This calculates the Fahrenheit equivalent of the Celsius temperature.
Step 2: Return the Result
- The result is returned by the function and printed using
console.log()
.
Conclusion
This JavaScript program demonstrates how to convert a temperature from Celsius to Fahrenheit using a simple mathematical formula. Temperature conversion is a common task in many programming scenarios, and this solution provides a straightforward way to handle it.
Comments
Post a Comment
Leave Comment