Concept

How can a C program compute the roots of a quadratic equation?

ComputerScienceOne / 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 ± sqrt(b^2 - 4ac)) / (2a). As before, we can create a basic program with a main() function 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. Thus, we have double a, b, c, root1, root2; printf(\"Please enter a: \"); scanf(\"%lf\", &a); printf(\"Please enter b: \"); scanf(\"%lf\", &b); printf(\"Please enter c: \"); scanf(\"%lf\", &c); Now to compute the roots: we need to take care that we correctly adapt the formula so it accurately reflects the order of operations. We also need to use the standard math library’s square root function (unless you want to write your own! We will write several square root methods as exercises later!). Carefully adapting the formula leads to root1 = (-b + sqrt(b*b - 4*a*c) ) / (2*a); root2 = (-b - sqrt(b*b - 4*a*c) ) / (2*a); Finally, we print the output using printf(). The full program can be found in Code Sample"

Related Ideas

How can a C program compute the roots of a quadratic equation? | ComputerScienceOne | Bifalgorithm | Bifalgorithm