CS 1440 Lab 2
Cover sheetPrevious ActivityNext Activity

Activity 2-8: Solving Quadratic Equations

Activity Procedure

We'll come back to tax rate determination in the homework portion of this lab. For now, let's detour into a problem you will surely remember from algebra: solving quadratic equations. The general quadratic equation is:

Ax2 + Bx + C = 0

and the solution(s) are given by the formula:

The formula describes, in a sneaky way, three different possibilities:

If B2 - 4AC is positive, then there are two real solutions: 

If B2 - 4AC is zero, there is a single real solution -B/(2A).

If B2 - 4AC is negative, there are no real solutions.

Try writing a complete program called quadratic.C which reads A, B, and C from the user, then prints the solution(s) of the quadratic equation, or a message that there are no solutions. You'll need to use the square root function sqrt, which is conveniently provided by the math library. To access this library, you'll need to add

#include <cmath>
to the top of your program. Here's a template for your program to get you started:

#include <iostream>
#include <cmath>

int main()
        double A,B,C,D;
        cout << "Enter A, B, C (without the commas): ";
        cin >> A >> B >> C;
        D = B*B - 4*A*C;
        // now your code should print 2, 1, or 0 solutions,
        // depending on whether D is positive, zero, or negative
        // If there are 2 solutions, you'll use sqrt(D) in your answers
        return 0;

You'll want to test your program for all three cases. Here is some handy data to check against:

x2 - x - 2 has two solutions: 2 and -1.

x2 - 2x + 1 has one solution: 1

x2 - x + 2 has no real solutions.

Work on this program until it works, or until you get stuck. In the latter case, you can look at  this solution  to point you in the right direction later.