Hi,

I am to write a program which should add and subtract any two polynomials of up to degree 4. I am also supposed to multiply two quadratic polynomials.

Two questions:

1. How to print out polynomials properly given how I decided to to do the math? Probably having used arrays may have been easier, But I really don't know. Also thinking of using if statements to block out the printing of -1, and 1 coefficients and to print out 0 when 0 is the appropriate answer, but how'd that go?

2. How to multiply two polynomials properly? (I know the arithmetic, just wondering how best to tackle it in code so you don't get confused)

This is what I have written at the moment, all help is appreciated! Thank you very much!

Code:

#include <iostream>
using namespace std;
class Polynomial
{
public:
Polynomial(int t1 = 0, int t2 = 0, int t3 = 0, int t4 = 0, int t5 = 0);
Polynomial calcSum(const Polynomial& p2);
Polynomial calcDifference(const Polynomial& p2);
Polynomial calcProduct(const Polynomial& p2);
void printPolynomial();
private:
int c0, c1, c2, c3, c4;
};
Polynomial :: Polynomial(int t1, int t2, int t3, int t4, int t5)
{
c0 = t1;
c1 = t2;
c2 = t3;
c3 = t4;
c4 = t5;
}
void Polynomial :: printPolynomial()
{
cout << c0 <<"x^4 + " << c1 << "x^3 + " << c2 << "x^2 + " << c3 << "x + " << c4 << endl; // this sort of works, but not really....
}
Polynomial Polynomial::calcSum(const Polynomial& p2)
{
Polynomial sum;
sum.c4 = c4 + p2.c4;
sum.c3 = c3 + p2.c3;
sum.c2 = c2 + p2.c2;
sum.c1 = c1 + p2.c1;
sum.c0 = c0 + p2.c0;
return sum;
}
Polynomial Polynomial::calcDifference(const Polynomial& p2)
{
Polynomial difference;
difference.c4 = c4 - p2.c4;
difference.c3 = c3 - p2.c3;
difference.c2 = c2 - p2.c2;
difference.c1 = c1 - p2.c1;
difference.c0 = c0 - p2.c0;
return difference;
}
int main()
{
Polynomial p1(1, 2, 3, -4, -5);
Polynomial p2(2, 3, -5, 6, 9);
Polynomial p3(1, 2, 3);
Polynomial p4(1, 2, 3);
cout << "The first polynomial is ";
p1.printPolynomial();
cout << "\nThe second polynomial is ";
p2.printPolynomial();
Polynomial sum = p1.calcSum(p2);
cout << "\n\nThe sum is ";
sum.printPolynomial();
Polynomial difference = p1.calcDifference(p2);
cout << "\nThe difference is ";
difference.printPolynomial();
cout << endl;
cout << "The first quadratic polynomial is ";
p3.printPolynomial();
cout << "The second quadratic polynomial is ";
p4.printPolynomial();
cout << endl << endl;
}