Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.4 kB
1
Indexable
Never
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <style>
        .calculator {
            max-width: 300px;
            margin: 50px auto;
            text-align: center;
            font-family: Arial, sans-serif;
        }
        .calculator input, .calculator button {
            margin: 5px;
            padding: 10px;
        }
        .calculator button {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="calculator">
        <h2>Simple Calculator</h2>
        <form id="calcForm">
            <input type="number" id="num1" placeholder="Enter first number" required>
            <input type="number" id="num2" placeholder="Enter second number" required>
            <br>
            <button type="button" onclick="calculate('add')">Add</button>
            <button type="button" onclick="calculate('subtract')">Subtract</button>
            <button type="button" onclick="calculate('multiply')">Multiply</button>
            <button type="button" onclick="calculate('divide')">Divide</button>
        </form>
        <br>
        <output id="result">Result will appear here</output>
    </div>

    <script>
        function calculate(operation) {
            const num1 = parseFloat(document.getElementById('num1').value);
            const num2 = parseFloat(document.getElementById('num2').value);
            const resultElement = document.getElementById('result');
            
            let result;

            switch (operation) {
                case 'add':
                    result = num1 + num2;
                    break;
                case 'subtract':
                    result = num1 - num2;
                    break;
                case 'multiply':
                    result = num1 * num2;
                    break;
                case 'divide':
                    if (num2 !== 0) {
                        result = num1 / num2;
                    } else {
                        result = 'Error: Division by zero';
                    }
                    break;
                default:
                    result = 'Invalid operation';
            }

            resultElement.textContent = result;
        }
    </script>
</body>
</html>
Leave a Comment