Bifalgorithm post · Computer science one · Quadratic Roots Revisited

How does the Java quadratic roots program check errors and calculate its roots?

How does the Java quadratic roots program check errors and calculate its roots? (Computer science one · Quadratic Roots Revisited) — "/**\n\n* This program com…

Ideas in this flowchart

  • Java program for computing the roots of a quadratic equation
  • Uses the quadratic formula to calculate the roots
  • Receives coefficients a, b, and c as command-line arguments
  • Are exactly three arguments provided?
  • Prints a usage message and exits when the argument count is invalid
  • Parses the three arguments as double-precision numbers
  • Is the coefficient a equal to zero?
  • Prints an error because a cannot be zero and exits
  • What type of roots does the discriminant indicate?
  • Prints an error when b² − 4ac is negative because complex roots are unsupported
  • Calculates and prints the single distinct root when b² − 4ac equals zero
  • Calculates and prints two roots when b² − 4ac is positive
Feed/

How does the Java quadratic roots program check errors and calculate its roots?

No cover

Channel

Computer science one

1 page

"/**\n\n* This program computes the roots to a quadratic equation\n\n* using the quadratic formula.\n\n*/\n\npublic class Roots {\n\npublic static void main(String args[]) {\n\ndouble a, b, c, root1, root2;\n\nif(args.length != 3) {\n\nSystem.err.println(\"Usage: a b c\n\n\");\n\nSystem.exit(1);\n\n}\n\na = Double.parseDouble(args[0]);\n\nb = Double.parseDouble(args[1]);\n\nc = Double.parseDouble(args[2]);\n\nif(a == 0) {\n\nSystem.err.println(\"Error: a cannot be zero\");\n\nSystem.exit(1);\n\n} else if(b*b < 4*a*c) {\n\nSystem.err.println(\"Error: cannot handle complex roots\n\n\");\n\nSystem.exit(1);\n\n} else if(b*b == 4*a*c) {\n\nroot1 = -b / (2*a);\n\nSystem.out.printf(\"Only one distinct root: %f\n\n\", root1);\n\n} else {\n\nroot1 = (-b + Math.sqrt(b*b - 4*a*c) ) / (2*a);\n\nroot2 = (-b - Math.sqrt(b*b - 4*a*c) ) / (2*a);\n\nSystem.out.printf(\"The roots of %fx^2 + %fx + %f are:\n\n\", a, b, c);\n\nSystem.out.printf(\" root1 = %f\n\n\", root1);\n\nSystem.out.printf(\" root2 = %f\n\n\", root2);\n\n}\n\n}\n\n}\n\nCode Sample 27.4.: Quadratic Roots Program in Java With Error Checking"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.