Back

Code Challenge: Quadratics

Difficulty  

divider

Objective

Solve a quadratic equation ax2 + bx + c = 0 using the quadratic formula.

The discriminant is b2 − 4ac, and its sign decides how many real roots exist. That makes this a conditionals problem as much as a math problem.

Skills to Practice

  • Prompting a user for input
  • Using math.sqrt() from Activity 1.9
  • Branching on a value you calculated yourself
  • Formatting custom output

Tasks

  • Create a new Python program named cc-quadratics.
  • Prompt the user for the coefficients a, b, and c.
  • Calculate the discriminant and display it.
  • If it is positive, there are two distinct real roots. Display both.
  • If it is zero, there is exactly one real root. Display it.
  • If it is negative, there are no real roots. Say so rather than letting the program crash.
  • Root formula: (−b ± √discriminant) ÷ 2a

Test all three branches. Try a=1, b=-3, c=2 for two roots, a=1, b=-2, c=1 for one, and a=1, b=0, c=1 for none. If you only ever test the first, you will never find out that math.sqrt() crashes on a negative number.


Sample Output

Sample Output
Enter the coefficient a: 1 [Enter]
Enter the coefficient b: -3 [Enter]
Enter the coefficient c: 2 [Enter]
Discriminant: 1
There are two real roots: 2.0 and 1.0
--- run again ---
Enter the coefficient a: 1 [Enter]
Enter the coefficient b: -2 [Enter]
Enter the coefficient c: 1 [Enter]
Discriminant: 0
There is one real root: 1.0
--- run again ---
Enter the coefficient a: 1 [Enter]
Enter the coefficient b: 0 [Enter]
Enter the coefficient c: 1 [Enter]
Discriminant: -4
There are no real roots.

Commence Challenge