Concept

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

ComputerScienceOne / Quadratic Roots Revisited

"Let’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 38.4.\n\n1 <?php\n\n2\n\n3 /**\n\n4 * This program computes the roots to a quadratic equation\n\n5 * using the quadratic formula.\n\n6 */\n\n7\n\n8 if($argc != 4) {\n\n9 printf(\"Usage: %s a b c\n\n\", $argv[0]);\n\n10 exit(1);\n\n11 }\n\n12\n\n13 $a = floatval($argv[1]);\n\n14 $b = floatval($argv[2]);\n\n15 $c = floatval($argv[3]);\n\n16\n\n17 if($a === 0) {\n\n18 printf(\"Error: a cannot be zero\n\n\");\n\n19 exit(1);\n\n20 } else if($b*$b < 4*$a*$c) {\n\n21 printf(\"Error: cannot handle complex roots\n\n\");\n\n22 exit(1);\n\n23 } else if($b*$b === 4*$a*$c) {\n\n24 $root1 = -$b / (2*$a);\n\n25 printf(\"Only one distinct root: %f\n\n\", $root1);\n\n26 } else {\n\n27 $root1 = (-$b + sqrt($b*$b - 4*$a*$c) ) / (2*$a);\n\n28 $root2 = (-$b - sqrt($b*$b - 4*$a*$c) ) / (2*$a);\n\n29\n\n30 printf(\"The roots of %fx^2 + %fx + %f are:\n\n\", $a, $b, $c);\n\n31 printf(\" root1 = %f\n\n\", $root1);\n\n32 printf(\" root2 = %f\n\n\", $root2);\n\n33 }\n\n34\n\n35 ?> Code Sample 38.4.: Quadratic Roots Program in PHP With Error Checking"

Related Ideas

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