如何用HTML按钮调用JavaScript函数,关联a、b、c数值输入并实现求解?
Got it, let's build a straightforward implementation that ties input fields to your a, b, c values and computes the solution when you click a button. Based on the values you provided (a=1, b=-3, c=-4), this example will solve a quadratic equation (since those coefficients map to (x^2 -3x -4 =0), which has roots 4 and -1).
Here's the full working code:
<!DOCTYPE html> <html> <head> <title>Quadratic Solver</title> </head> <body> <h3>Enter Quadratic Coefficients (ax² + bx + c = 0)</h3> <div> <label for="a">a:</label> <input type="number" id="a" placeholder="Enter a"> </div> <div> <label for="b">b:</label> <input type="number" id="b" placeholder="Enter b"> </div> <div> <label for="c">c:</label> <input type="number" id="c" placeholder="Enter c"> </div> <br> <button onclick="calculateRoots()">Calculate Roots</button> <div id="result"></div> <script> function calculateRoots() { // Get values from input fields and convert to numbers const a = Number(document.getElementById('a').value); const b = Number(document.getElementById('b').value); const c = Number(document.getElementById('c').value); // Validate input (make sure a isn't zero, since it's quadratic) if (a === 0) { document.getElementById('result').textContent = "a cannot be 0 for a quadratic equation!"; return; } // Calculate discriminant const discriminant = b * b - 4 * a * c; const resultDiv = document.getElementById('result'); // Determine roots based on discriminant value if (discriminant > 0) { const root1 = (-b + Math.sqrt(discriminant)) / (2 * a); const root2 = (-b - Math.sqrt(discriminant)) / (2 * a); resultDiv.textContent = `Two real roots: x = ${root1.toFixed(2)} and x = ${root2.toFixed(2)}`; } else if (discriminant === 0) { const root = (-b) / (2 * a); resultDiv.textContent = `One real root: x = ${root.toFixed(2)}`; } else { const realPart = (-b) / (2 * a); const imaginaryPart = Math.sqrt(-discriminant) / (2 * a); resultDiv.textContent = `Complex roots: x = ${realPart.toFixed(2)} + ${imaginaryPart.toFixed(2)}i and x = ${realPart.toFixed(2)} - ${imaginaryPart.toFixed(2)}i`; } } </script> </body> </html>
How it works:
- The three input fields are linked to
a,b,cvia theiridattributes. - When you click the Calculate Roots button, it triggers the
calculateRoots()JavaScript function. - The function fetches the input values, converts them to numbers, then calculates the discriminant to determine the type of roots.
- For your test values (a=1, b=-3, c=-4), the discriminant is ( (-3)^2 - 41(-4) = 9 +16 =25 ), so you'll get two real roots: 4.00 and -1.00.
Notes:
- The input fields use
type="number"to ensure users can only enter numeric values. - We added validation to prevent
afrom being 0 (since that would make it a linear equation, not quadratic). - Results are rounded to two decimal places for readability using
toFixed(2).
内容的提问来源于stack exchange,提问作者DimityrU
相关产品推荐
相关产品推荐

