Page 388 - Web_Application_v2.0_C12_Fb
P. 388

19.   Write a JavaScript code to input three real numbers as arguments of main( ) method and calculate the
                    roots of the quadratic equation using the following formula:

                        b
                       -  ±  b 2 -4ac
                    x =
                            2a
                    Where, b  - 4ac is known as the determinant of a quadratic equation. [Math function]
                            2
                Ans.  <!DOCTYPE html>
                   <HTML>
                   <HEAD>
                   <TITLE>Quadratic Equation Roots Calculator</TITLE>
                   </HEAD>

                   <BODY>
                   <H1>Quadratic Equation Roots Calculator</H1>
                   <P>Enter the coefficients of the quadratic equation:</P>
                   a = <INPUT TYPE="number" ID="a" PLACEHOLDER="a"><BR><BR>
                   b = <INPUT TYPE="number" ID="b" PLACEHOLDER="b"><BR><BR>
                   c = <INPUT TYPE="number" ID="c" PLACEHOLDER="c"><BR><BR>
                   <BUTTON ONCLICK="calculateRoots()">Calculate Roots</BUTTON>
                   <P ID="result"></P>

                   <SCRIPT>
                   function calculateRoots() {
                   let a = parseFloat(document.getElementById('a').value);
                   let b = parseFloat(document.getElementById('b').value);
                   let c = parseFloat(document.getElementById('c').value);
                   if (isNaN(a) || isNaN(b) || isNaN(c)) {
                   document.getElementById("result").innerHTML = "Please enter valid numbers for
                   all coefficients.";
                   return;
                   }
                   let determinant = b * b - 4 * a * c;
                   let root1, root2;
                   if (determinant > 0) {

                   root1 = (-b + Math.sqrt(determinant)) / (2 * a);
                   root2 = (-b - Math.sqrt(determinant)) / (2 * a);
                   document.getElementById("result").innerHTML = `The roots are: ${root1.
                   toFixed(2)} and ${root2.toFixed(2)}`;
                   } else if (determinant === 0) {
                   root1 = root2 = -b / (2 * a);
                   document.getElementById("result").innerHTML = `The roots are equal: ${root1.
                   toFixed(2)}`;
                   } else {
                   let realPart = (-b / (2 * a)).toFixed(2);


                386   Touchpad Web Applications (Ver. 2.0)-XII
   383   384   385   386   387   388   389   390   391   392   393