The goal of assignment 4 is to reinforce the dynamic classes in C++. Specificall
ID: 3667994 • Letter: T
Question
The goal of assignment 4 is to reinforce the dynamic classes in C++. Specifically, the assignment is to implement the polynomial class ,but the additional requirement is to implement the class using a dynamic array to store the coefficients. The class needs to have a destructor, copy constructor, and an overloaded assignment operator. Need help with the implementation class and modified header file.
//Header File
class polynomial
{
public:
// CONSTANTS
static const unsigned int CAPACITY = 30;
static const unsigned int MAX_EX = CAPACITY - 1;
// CONSTRUCTOR
polynomial(double c = 0.0, unsigned int exponent = 0);
// MODIFICATION MEMBER FUNCTIONS
void add_to_coef(double amount, unsigned int exponent);
void assign_coef(double coefficient, unsigned int exponent);
void clear( );
// CONSTANT MEMBER FUNCTIONS
double coefficient(unsigned int exponent) const;
unsigned int degree( ) const { return current_degree; }
//polynomial derivative( ) const;
double eval(double x) const;
unsigned int next_term(unsigned int e) const;
unsigned int previous_term(unsigned int e) const;
// CONSTANT OPERATORS
double operator( ) (double x) const { return eval(x); }
private:
double coef[CAPACITY];
unsigned int current_degree;
void compute_degree();
};
// NON-MEMBER BINARY OPERATORS
polynomial operator +(const polynomial& p1, const polynomial& p2);
polynomial operator -(const polynomial& p1, const polynomial& p2);
//polynomial operator *(const polynomial& p1, const polynomial& p2);
// NON-MEMBER OUTPUT FUNCTIONS
std::ostream& operator << (std::ostream& out, const polynomial& p);
}
#endif
Explanation / Answer
Can help you with this
#include <iostream>
using namespace std;
class Polynomial
{
private:
int Nterms;
double* pCoeffs;
public:
double evaluateAt(double x);
void print(void);
Polynomial( double Coeffs[], int N_terms );
~Polynomial();
};
Polynomial::Polynomial( double Coeffs[], int N_terms )
{
Nterms = N_terms;
pCoeffs = new double[ Nterms ];
for(int i=0; i<Nterms; i++)
pCoeffs[i] = Coeffs[i];
}
Polynomial::~Polynomial()
{
if( pCoeffs )
{
delete [] pCoeffs;
pCoeffs = NULL;
}
}
double Polynomial::evaluateAt(double x)
{
double sum = 0.0;
double xPow = 1.0;
if( pCoeffs )
for(int i=0; i<Nterms; i++)
{
sum += xPow*pCoeffs[i];
xPow *= x;
}
return sum;
}
Example purpose use:
void Polynomial::print(void)
{
std::cout << pCoeffs[Nterms-1] << "x^" << Nterms-1;
for(int i=Nterms-2; i>=0; i--)
std::cout << " + " << pCoeffs[i] << "x^" << i;
return;
}
int main(void)
{
double Cnum[5] = { 19.0, 29.0, 1.0, 10.0, 8.0 };
Polynomial Pnum( Cnum, 5 );
cout << "Pnum = ";
Pnum.print();
cout << " Pnum(2.0) = " << Pnum.evaluateAt(2.0) << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.