Problem Session Working in pairs of two, solve the following problem...

advertisement
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.
root1 
b
b
2
2a
 4ac
root 2 
b
b
2
 4ac
2a
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
a
b
c
b2-4ac
diagnostic
double
double
double
double
string
Kind
varying
varying
varying
varying
constant
Name
a
b
c
temp
--
OCD: Operations
Description
Predefined? Library?
receive doubles
check preconds
compute root
- multiply doubles
- add doubles
- subtract doubles
- divide doubles
- square root
return a double
yes
yes
no
yes
yes
yes
yes
yes
yes
Name
--cassert
assert()
--built-in
*
built-in
+
built-in
built-in
/
cmath
sqrt()
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”
#include <cmath>
#include <cassert>
using namespace std;
// prototypes
// sqrt()
// assert()
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);
Download