Bifalgorithm post · Computer science one · Computing Quadratic Roots

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

How can a C program compute the roots of a quadratic equation? (Computer science one · Computing Quadratic Roots) — "Some programs require the user to enter mu…

Ideas in this flowchart

  • A program prompts for quadratic coefficients and computes the roots
  • The program uses a main() function as its basic structure
  • The prompt-input process is repeated for multiple inputs
  • Prompt for and read coefficient a
  • Prompt for and read coefficient b
  • Prompt for and read coefficient c
  • The program declares variables for the coefficients and roots
  • Three double variables store a, b, and c
  • Two double variables store root1 and root2
  • The roots are computed with the quadratic formula
  • The formula must be adapted carefully to preserve the order of operations
  • The computation uses the standard math library square root function
  • root1 = (-b + sqrt(b*b - 4*a*c)) / (2*a)
  • root2 = (-b - sqrt(b*b - 4*a*c)) / (2*a)
  • The program prints the computed output using printf()
  • The complete program is available in the Code Sample
Feed/

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

No cover

Channel

Computer science one

1 page

"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"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.