Concept
What is 26?
ComputerScienceOne / Computing Quadratic Roots
"26. Basics 26.6.2. Computing Quadratic Roots Some programs require the user to enter multiple inputs. The prompt-input process can be repeated. In this example, consider asking the user for the coefficients, a, b, c to a quadratic polynomial, ax 2 + bx + c and computing its roots using the quadratic formula, x = − b ± √ b 2 − 4 ac 2 a As before, we can create a basic program with a main() method and start filling in the details. In particular, we’ll need to prompt for the input a , then read it in; then prompt for b , read it in and repeat for c . We’ll also need several variables: three for the coefficients a, b, c and two more; one for each root. 1 double a, b, c, root1, root2; 2 Scanner s = new Scanner(System.in); 3 4 System.out.println(\"Please enter a: \"); 5 a = s.nextDouble(); 6 System.out.println(\"Please enter b: \"); 7 b = s.nextDouble(); 8 System.out.println(\"Please enter c: \"); 9 c = s.nextDouble(); Now to compute the roots: we need to adapt the formula so it accurately reflects the order of operations. We also need to use the standard math library’s square root method. 1 root1 = (-b + Math.sqrt(b*b - 4*a*c) ) / (2*a); 2 root2 = (-b - Math.sqrt(b*b - 4*a*c) ) / (2*a); Finally, we print the output using System.out.printf() . The full program can be found in Code Sample 26.4. This program was interactive. As an alternative, we could have read all three of the inputs as command line arguments, taking care that we need to convert them to floating point numbers. Lines 16–21 in the program could have been changed to 400"
Related Ideas
- How can a C program compute the roots of a quadratic equation?ComputerScienceOne · Computing Quadratic Roots
- How does the Java quadratic roots program check errors and calculate its roots?ComputerScienceOne · Quadratic Roots Revisited
- How can quadratic-equation inputs be provided as command-line arguments?ComputerScienceOne · Computing Quadratic Roots
- What kinds of user input can cause problems in a quadratic-roots program?ComputerScienceOne · Computing Quadratic Roots
- How do you read numeric input from a user in Java with Scanner?ComputerScienceOne · Converting Units
- How does PHP compute the roots of a quadratic equation?ComputerScienceOne · Computing Quadratic Roots
- How can a PHP program prompt for the coefficients of a quadratic polynomial?ComputerScienceOne · Computing Quadratic Roots
- How can conditionals handle invalid inputs and special cases in a quadratic roots program?ComputerScienceOne · Quadratic Roots Revisited