90 likes | 103 Views
Implement a quadratic library in C++ using Object-oriented Design to compute roots of equations and handle errors efficiently.
E N D
Problem Session Working in pairs of two, solve the following problem...
Problem Using OCD, design and implement a quadratic library that provides functions to compute the roots of a quadratic equation. Your functions should check for likely errors (i.e., a equal to zero, negative b2-4ac, etc.)
OCD: Behavior Our functions should receive a, b, and c from its caller. Each should check that a != 0, compute b2-4ac and check that it is positive, and display diagnostic messages and terminate if either is false. Function Root1() should return the root where addition is performed, while Root2() should return the root where subtraction is performed.
OCD: Objects Description Type Kind Name a double varying a b double varying b c double varying c b2-4ac double varying temp diagnostic string constant --
OCD: Operations Description Predefined? Library? Name receive doubles yes -- -- check preconds yes cassert assert() compute root no -- -- - multiply doubles yes built-in * - add doubles yes built-in + - subtract doubles yes built-in - - divide doubles yes built-in / - square root yes cmath sqrt() return a double yes built-in return
OCD: Algorithm 0. Receive a, b, c. 1. Compute temp = b2-4ac. 2. Assert preconditions are true. 3. Root1: return (-b + sqrt(temp))/2a. Root2: return (-b - sqrt(temp))/2a.
Coding: quadratic.h /* quadratic.h * Author: J. Adams. * Date: january 1998. * Purpose: Prototypes of functions to compute * quadratic roots. */ double Root1(double a, double b, double c); double Root2(double a, double b, double c);
Coding: quadratic.cpp /* quadratic.cpp * Author: J. Adams. * Date: january 1998. * Purpose: Definitions of functions for quadratic roots. */ #include “quadratic.h” // prototypes #include <cmath> // sqrt() #include <cassert> // assert() using namespace std; double Root1(double a, double b, double c) { double temp = b*b - 4*a*c; assert(a != 0 && temp > 0); return (-b + sqrt(temp))/2*a; } // ... Define Root2() here in a similar fashion
Coding: quadratic.doc /* quadratic.doc * Author: J. Adams. * Date: january 1998. * Purpose: Documentation of functions to compute * quadratic roots. */ /****************************************************** * Compute the roots of a quadratic. * * Receive: a, b, c, the coefficients of a quadratic. * * Precondition: a != 0 && b^2-4ac > 0. * * Return: Root1: the “-b + sqrt...” root. * * Root2: the “-b - sqrt...” root. * ******************************************************/ double Root1(double a, double b, double c); double Root2(double a, double b, double c);