//Poly.h #ifndef _POLY_H #define _POLY_H #include using namespace std; const int CAPACITY = 100; class Poly { private: int degree; // degree int coefs[CAPACITY]; //coefficient array public: Poly(); //constructor ~Poly(); //destructor void display(ostream& out) const; void input(istream& in); int evaluate(int x); Poly operator+(const Poly& p); Poly operator*(const Poly& p); }; ostream& operator<<(ostream& out, const Poly& p); istream& operator>>(istream& in, Poly& p); #endif ///////////////////////// //Poly.cpp #include "Poly.h" //constructor Poly::Poly() : degree(0) { for (int i = 0; i < CAPACITY; i++) //very important later coefs[i] = 0; } //destructor Poly::~Poly() { } void Poly::input(istream& in) { cout << "Input the polynomial degree (< " << CAPACITY/2 << "): "; in >> degree; for (int i = 0; i <= degree; i++) { cout << "Input coefficient for degree of " << i << ": "; in >> coefs[i]; } } void Poly::display(ostream& out) const { for (int i = degree; i >= 0; i--) { if (i > 0) out << coefs[i] << "*" << "x^" << i << " + "; else out << coefs[i]; } out << endl; } //overloading operator+ Poly Poly::operator+(const Poly& p) { Poly temp; temp.degree = (degree > p.degree) ? degree : p.degree; //take higher degree int i; for (i = 0; i <= degree && i <= p.degree; i++) temp.coefs[i] = coefs[i] + p.coefs[i]; for ( ; i <= degree; i++) temp.coefs[i] = coefs[i]; for ( ; i <= p.degree; i++) temp.coefs[i] = p.coefs[i]; return temp; } //overloading operator* Poly Poly::operator*(const Poly& p) { Poly temp; temp.degree = degree + p.degree; //get the highest degree for (int i = 0; i <= degree; i++) for (int k = 0; k <= p.degree; k++) temp.coefs[i+k] += coefs[i] * p.coefs[k]; return temp; } int Poly::evaluate(int x) { int ret = 0; for (int i = degree; i >= 0; i--) ret = ret * x + coefs[i]; return ret; } ostream& operator<<(ostream& out, const Poly& p) { p.display(out); return out; } istream& operator>>(istream& in, Poly& p) { p.input(in); return in; }
This is a personal WEB site developed and maintained by an individual and not by Seattle University. The content and link(s) provided on this site do not represent or reflect the view(s) of Seattle University. The individual who authored this site is solely responsible for the site's content. This site and its author are subject to applicable University policies including the Computer Acceptable Use Policy (www.seattleu.edu/policies).