How to create a quadratic equation solver
- Web Coding

 - Sep 8, 2020
 - 1 min read
 
Updated: Sep 10, 2020
Learn how to create a quadratic equation solver using only HTML, CSS and JavaScript
HTML and CSS
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <style>
 body{
 min-height: 100vh;
 display: flex;
 align-items: center;
 justify-content: center;
        }
 </style>
</head>
<body>
 <div>
 <p>Input:</p>
    a: <input type="number" name="a" id="a"> <br>
    b: <input type="number" name="b" id="b"> <br>
    c: <input type="number" name="c" id="c"> <br>
 <button id="calcBtn">Calculate</button>
 <p id="resultDisplay">x = or x = </p>
 </div>
 <script src="script.js"></script>
</body>
</html>JavaScript
let a = document.getElementById('a');
let b = document.getElementById('b');
let c = document.getElementById('c');
let calcBtn = document.getElementById('calcBtn');
let resultDisplay = document.getElementById('resultDisplay');
calcBtn.addEventListener('click', calculate);
function calculate(){
 let a1 = a.value;
 let b1 = b.value;
 let c1 = c.value;
 a1 = parseFloat(a1);
 b1 = parseFloat(b1);
 c1 = parseFloat(c1);
 let bPower = Math.pow(b1, 2);
 let fourAC = (4 * a1 * c1);
 let resultToBeSquared = bPower - fourAC;
 let squareRoot = Math.sqrt(resultToBeSquared);
 let bottomOfEquation = (2 * a1);
 if (isNaN(squareRoot) === true){
 resultDisplay.innerHTML = 'Impossible to solve';
    }
 else {
 let result1 = (-b1 - squareRoot) / bottomOfEquation;
 let result2 = (-b1 + squareRoot) / bottomOfEquation;
 resultDisplay.innerHTML = "x = " + result1 + " or x = " + result2;
    }
}If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on
YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ
Instagram: https://www.instagram.com/coding_for_the_web/
Twitter: https://twitter.com/LearnWebCoding



Comments