Write a C++ program which has a main-driver and creat a polynomial class Polynom
ID: 3891828 • Letter: W
Question
Write a C++ program which has a main-driver and
creat a polynomial class Polynom which has 2 attributes, an array of:
double coefficients[] = coefficients of the terms of the polynomial whose powers of x
are the indices of the array (going from 0 to n)
and n which is the size of the array (the normal upper limit of indicies).
So, for example, the cubic polynomial: 9.2 * x^3 + 6.1 * x^2 + 3.9 * x + 17.3
is stored as an array coefficients[] = {17.3 , 3.9 , 6.1 , 9.2 };
and n = 3.
Constructors, accessors, mutators, and any other member functions needed
should be written, too, including (minimally):
constructor (a good one which feeds coefficients[] and n
from 2 parameters, array of doubles and an integer )
overload the operators =, + , -, * , / , % , and output with <<
to do the following respectively:
= polynomial assignment
+ polynomial addition
- polynomial subtraction
* polynomial multiply
/ polynomial division
% polynomial remainder
and member functions:
setTerm = mutator to assign 1 coefficient at power index desired
(maybe need to add 0-coefficients to compensate (i.e. no blanks)
setPoly = fills polynomial from keyboard with powers and coefficients
printPoly = dumps polynomial as a formatted output to the screen
like for the above example: 9.2 * x^3 + 6.1 * x^2 + 3.9 * x + 17.3
Make sure the main driver tests all the overloaded arithmetic operators, assignment and <<
operator as follows:
Test the constructor to fill Polynomials
A = 1 * x^3 + 3 * x^2 + 3 * x + 1
and
B = x^2 + 2 * x + 1
then do:
cout << A + B << endl << endl;
cout << A - B << endl << endl;
cout << A * B << endl << endl;
cout << A / B << endl << endl;
cout << A % B << endl << endl;
Also make sure your driver tests toroughly every member function
Explanation / Answer
#include <iostream>
using namespace std;
class Polynom {
private :
double coefficients[];
int degree;
public :
Polynom(double array[],int degree1){
degree = degree1;
cout<<"Print in constructor"<< ' ';
for (int index=0;index<degree;index++){
coefficients[index] = array[index];
}
cout<< ' ';
}
void printPoly()
{
for (int i=0; i<degree; i++)
{
cout << coefficients[i];
if (i != 0)
cout << "x^" << i ;
if (i != degree-1)
cout << " + ";
}
}
Polynom operator + (double B[]) {
int size =(int) sizeof(B) / sizeof(B[0]);
double *sum = new float[size];
for (int i = 0; i<degree; i++)
sum[i] = coefficients[i];
for (int i=0; i<size; i++)
sum[i] += B[i];
return Polynom(sum,size);
}
Polynom operator * (int B[]){
int size =(int) sizeof(B) / sizeof(B[0]);
double *prod = new double[degree+size-1];
for (int i = 0; i<degree+size-1; i++)
prod[i] = 0;
for (int i=0; i<degree; i++)
{
for (int j=0; j<size; j++)
prod[i+j] += coefficients[i]*B[j];
}
return Polynom(prod,size);
}
};
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.