Solution Files
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exercise 2 - Temperature Converter</title>
</head>
<body>
<h1>Exercise 2: Temperature Converter</h1>
<script src="script.js"></script>
</body>
</html>
script.js
// Get temperature value from user
let tempInput = prompt("Enter a temperature value:");
let tempValue = Number(tempInput);
// Get unit from user
let unit = prompt("Enter the unit (C for Celsius, F for Fahrenheit):").toUpperCase();
// Check if input is valid
if (isNaN(tempValue)) {
document.write("<p>Error: Please enter a valid number.</p>");
} else if (unit !== 'C' && unit !== 'F') {
document.write("<p>Error: Please enter 'C' for Celsius or 'F' for Fahrenheit.</p>");
} else {
let convertedTemp;
let convertedUnit;
if (unit === 'C') {
// Convert Celsius to Fahrenheit
convertedTemp = (tempValue * 9/5) + 32;
convertedUnit = 'F';
document.write(`<p>${tempValue}°C is equal to ${convertedTemp.toFixed(2)}°F</p>`);
} else {
// Convert Fahrenheit to Celsius
convertedTemp = (tempValue - 32) * 5/9;
convertedUnit = 'C';
document.write(`<p>${tempValue}°F is equal to ${convertedTemp.toFixed(2)}°C</p>`);
}
}