Concept

How can conditionals handle invalid inputs and special cases in a quadratic roots program?

ComputerScienceOne / Quadratic Roots Revisited

"16.3.3. Quadratic Roots Revisited\n\nLet’s return to the quadratic roots program we previously designed that uses the quadratic equation to compute the roots of a quadratic polynomial by reading coefficients a, b, c in from the user. One of the problems we had previously identified is if the user enters “bad” input: if a = 0, we would end up dividing by zero; if b 2 − 4 ac < 0 then we would have complex roots. With conditionals, we can now check for these issues and exit with an error message. Another potential case we might want to handle differently is when there is only one distinct root ( b 2 − 4 ac = 0). In that case, the quadratic formula simplifies to − b 2 a and we can print a different, more specific message to the user. The full program can be found in Code Sample 16.4.\n\n1 #include <stdlib.h>\n\n2 #include <stdio.h>\n\n3 #include <math.h>\n\n4\n\n5 /**\n\n6 * This program computes the roots to a quadratic equation\n\n7 * using the quadratic formula.\n\n8 */\n\n9 int main(int argc, char **argv) {\n\n10\n\n11 double a, b, c, root1, root2;\n\n12\n\n13 if(argc !=4) {\n\n14 printf(\"Usage: %s a b c\n\n\", argv[0]);\n\n15 exit(1);\n\n16 }\n\n17\n\n18 a = atof(argv[1]);\n\n19 b = atof(argv[2]);\n\n20 c = atof(argv[3]);\n\n21\n\n22 if(a == 0) {\n\n23 printf(\"Error: a cannot be zero\n\n\");\n\n24 exit(1);\n\n25 } else if(b*b < 4*a*c) {\n\n26 printf(\"Error: cannot handle complex roots\n\n\");\n\n27 exit(1);\n\n28 } else if(b*b == 4*a*c) {\n\n29 root1 = -b / (2*a);\n\n30 printf(\"Only one distinct root: %f\n\n\", root1);\n\n31 } else {\n\n32 root1 = (-b + sqrt(b*b - 4*a*c) ) / (2*a);\n\n33 root2 = (-b - sqrt(b*b - 4*a*c) ) / (2*a);\n\n34\n\n35 printf(\"The roots of %fx^2 + %fx + %f are:\n\n\", a, b, c);\n\n36 printf(\" root1 = %f\n\n\", root1);\n\n37 printf(\" root2 = %f\n\n\", root2);\n\n38 }\n\n39 return 0;\n\n40 } Code Sample 16.4.: Quadratic Roots Program in C With Error Checking"

Related Ideas

How can conditionals handle invalid inputs and special cases in a quadratic roots program? | ComputerScienceOne | Bifalgorithm | Bifalgorithm