Concept

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

ComputerScienceOne / Quadratic Roots Revisited

"/**\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"

Related Ideas

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