i have this question:
You will implement a polynomial class that uses a dynamic array to store the polynomial's coefficients. The Polynomial class has two private members variables: a dynamic array to store the coefficients and the degree of the polynomial like so:
(private: double *coef; // Pointer to the dynamic array
int degree; // the polynomial degree)
1.Write the constructors permitting the initialization of simple polynomials of the following way:
i. Polynomial p1(3,1); // polynomial of degree 1 p1 = 3 x+1
ii. Polynomial p2(1,4,2); // polynomial of degree 2 p2 = x2+4x+2
iii. Polynomial p3(1,3,3,1); // polynomial of degree 3 p3 = x3+ 3x2 + 3x +1
that is the question.
these constructors are being handed the coefficients but the number of coefficients is chosen by the user, how do i make such constructor(s)?? and i cant put a limit on the degree of the polynomial the user wants to enter(if this were the case, i could put default values that are zero so that if he doesnt give all coefficinets, the rest of coefficients will be zero)
is the dynamic array member going to help in this problem?
I suggest creating a struct Term
:
struct Term
{
int coefficient;
int power;
};
A polynomial, by definition is a container (or sum) of terms:
class Polynomial
{
public:
std::vector<Term> terms;
Polynomial(int coef1, int constant1);
}
In the above class, the constructor will create two terms:
Polynomial::Polynomial(int coef1, int constant1)
{
Term t1;
Term c;
t1.coefficient = coef1;
t1.power = 1;
c.coefficient = constant1;
c.power = 0;
terms.push_back(c);
terms.push_back(t1);
}
The next constructor, in your requirements, creates 3 terms:
Polynomial::Polynomial(int coef1, int coef2, int constant1)
{
Term t1 = {coef1, 2};
Term t2 = {coef2, 1};
Term constant_term = {constant1, 0};
terms.push_back(constant_term);
terms.push_back(t2);
terms.push_back(t1);
}
One of the theorems of addition is that the terms can be in any order. You can change the order that you append them to the container so you print them in common order (highest exponent term first).
In the requirements, there is double * coef
which is supposed to be an array of coefficients (one for each term).
Here's one example of a constructor:
Polynomial::Polynomial(double coef1, double constant)
{
degree = 1;
coef = new double[2]; // 2 terms.
coef[0] = coef1;
coef[1] = constant;
}
The other constructors are similar to the above one.
Remember, your destructor should contain delete[] coef;
.