ex3-6.cpp - Example 3-6 The quadratic (equation) class

// File:  ex3-6.cpp - the quadratic class

#include <iostream>
#include <cmath>
using namespace std;

class quadratic
{
private:
    float a, b, c;
public:
    void set(float f1, float f2, float f3)
	{a = f1; b = f2; c = f3; return;}
    void solve(void) const;
    void display(void) const;
};

void quadratic::solve (void) const
{
	bool complex_roots;
	float radical_stuff;
	if (a == 0)
	{
		cout << "This is not a quadratic equation.  It has only one root "
			<< -c/b << endl;
		return;
	}
	complex_roots = (radical_stuff = b * b - 4 * a * c) < 0;
	cout << "The roots of the equation are ";
	if (!complex_roots)
		cout << ((-b+sqrt(radical_stuff))/(2.*a))
		<<" and " << ((-b-sqrt(radical_stuff))/(2.*a)) << endl;
	else
		cout << (-b/(2.*a)) << '+' << sqrt(-radical_stuff)/(2.*a) << 'i'
		<<
		" and "
		<< (-b/(2.*a)) << '-' << sqrt(-radical_stuff)/(2.*a) << 'i'
		<<endl;
	return;
}

void quadratic::display(void) const
{
	cout << "The coefficients of the quadratic equations are: "
		<< a << ", " << b << ", and " << c <<endl;
	return;
}

int main(void)
{
	quadratic equation;
	float a,b,c;
	while (1)
	{
		cout << "Enter 3 coeffients for a quadratic equation (or quit) => ";
		if (!(cin >> a >> b >> c)) break;
		equation.set(a,b,c);
		equation.display();
		equation.solve();
		cout << endl;
	}

	return 0;
}



CIS27: Programming in C++    Instructor: Joe Bentley