calculator
Thu Nov 21 2024 18:01:46 GMT+0000 (Coordinated Universal Time)
Saved by @coding1
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scientific Calculator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="calculator">
<input type="text" id="display" disabled>
<div class="buttons">
<button onclick="clearDisplay()">C</button>
<button onclick="appendToDisplay('7')">7</button>
<button onclick="appendToDisplay('8')">8</button>
<button onclick="appendToDisplay('9')">9</button>
<button onclick="appendToDisplay('/')">/</button>
<button onclick="appendToDisplay('4')">4</button>
<button onclick="appendToDisplay('5')">5</button>
<button onclick="appendToDisplay('6')">6</button>
<button onclick="appendToDisplay('*')">*</button>
<button onclick="appendToDisplay('1')">1</button>
<button onclick="appendToDisplay('2')">2</button>
<button onclick="appendToDisplay('3')">3</button>
<button onclick="appendToDisplay('-')">-</button>
<button onclick="appendToDisplay('0')">0</button>
<button onclick="appendToDisplay('.')">.</button>
<button onclick="calculate()">=</button>
<button onclick="appendToDisplay('+')">+</button>
<button onclick="calculate('sqrt')">√</button>
<button onclick="calculate('pow')">x²</button>
<button onclick="calculate('sin')">sin</button>
<button onclick="calculate('cos')">cos</button>
<button onclick="calculate('tan')">tan</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f4;
font-family: Arial, sans-serif;
}
.calculator {
background-color: white;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
padding: 20px;
width: 300px;
}
#display {
width: 100%;
height: 40px;
text-align: right;
font-size: 24px;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 10px;
padding: 5px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
button {
height: 40px;
font-size: 18px;
border: none;
border-radius: 5px;
background-color: #007bff;
color: white;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #0056b3;
}
script.js
function appendToDisplay(value) {
document.getElementById("display").value += value;
}
function clearDisplay() {
document.getElementById("display").value = "";
}
function calculate(operation) {
const display = document.getElementById("display");
let result;
try {
if (operation === 'sqrt') {
result = Math.sqrt(eval(display.value));
} else if (operation === 'pow') {
result = Math.pow(eval(display.value), 2);
} else if (['sin', 'cos', 'tan'].includes(operation)) {
const angle = eval(display.value) * (Math.PI / 180); // Convert to radians
result = Math[operation](angle);
} else {
result = eval(display.value);
}
display.value = result;
} catch (error) {
display.value = "Error!";
}
}



Comments