Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
Difficulty: 2/10
Date added: 21th of July 2008
In this exercise you must refactor a class that is given as an example in reference [0] . You will learn how to think to correctly refactor a class and that literature does not always set a good examples.
A quadratic equation is an equation in the form 'ax2 + bx + c = 0'. For which x or x's is this true? The number of solutions this equation has is determined by the discrimant: D = b2 - 4ac. If D is smaller then zero, the equation has no solutions. If D equals zero, the solution to the equation is x = -b/2a. If D is bigger then zero, the solutions are x = (-b-sqrt(D)) / (2a) and x = (-b+sqrt(D)) / (2a).
Below of a piece of code (from [0] ) demonstrating a class to solve a quadratic equation. Can you refactor this class to follow good class design, method design, function design and good thinking?
class Qs
{
void coeff(double aa, double bb, double cc)
{
a = aa;
b = bb;
c = cc;
}
bool solve()
{
double D = b * b - 4 * a * c;
if (a == 0 || D < 0) return false;
x1 = (-b + rD)/(2 * a);
x2 = (-b - rD)/(2 * a);
}
double root1() const { return x1; }
double root2() const { return x2; }
double a,b,c,x1,x2;
};
View the answer of this exercise.
Feel free to post your feedback about this exercise at Programmer's Heaven.
[0] Leen Ammeraal. C++ (6th edition). ISBN: 90-395-1935-8. 2001.
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.