Bifalgorithm post · Computer science one · Computing Quadratic Roots

What is 26?

What is 26? (Computer science one · Computing Quadratic Roots) — "26. Basics 26.6.2. Computing Quadratic Roots Some programs require the user to enter multiple…

Ideas in this flowchart

  • Computing quadratic roots with a program
  • The program uses a main() method as its basic structure.
  • The user enters the coefficients a, b, and c of ax² + bx + c.
  • The prompt-and-input process is repeated for a, b, and c.
  • Variables are needed for a, b, c and the two roots.
  • The roots are computed with the quadratic formula.
  • The formula must be written to preserve the correct order of operations.
  • Math.sqrt() supplies the square-root operation.
  • The program prints the computed roots with System.out.printf().
  • The complete interactive program appears in Code Sample 26.4.
  • Alternatively, all three inputs can be supplied as command-line arguments.
  • Command-line arguments must be converted to floating-point numbers.
Feed/

What is 26?

No cover

Channel

Computer science one

1 page

"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"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.