aaronmk2 0 Junior Poster in Training

I am writing a program where the user inputs two polynomials, then the program adds them, multiplies them, and evaluates one of them. I am having two problems. First, I can't think of how to add the exponents in the overloaded method for *. Second when the two polynomials multiply it returns 0 after the shorter polynomial ends.

#include <iostream>
using namespace std;
#ifndef _POLY_H
#define _POLY_H
const int CAPACITY =100;


class Poly {
public:
	Poly();
	~Poly();
	void display(ostream & out)const;
	void input(istream &in);
	int evaluate(int x);
	Poly operator+(const Poly &p);
	Poly operator *(const Poly &p);
private:
	int degree;
	int coefs[CAPACITY];
};
ostream & operator<<(ostream & out, const Poly & p);
istream & operator>>(istream &in, Poly &p);
#endif



#include "Poly.h"
#include <iostream>
#include <cmath>
using namespace std;

Poly::Poly():degree(0){
	for (int i=0; i<CAPACITY; i++) {
		coefs[i]=NULL;
	}
}
Poly::~Poly(){
}
void Poly::display(ostream &out)const{
	for (int i=0; i<degree; i++) {
		out<<coefs[i]<<"x^"<<i<<" + ";
	}
	for (int i=degree; i<degree+1; i++) {
		out<<coefs[i]<<"x^"<<i;
	}
	
}
void Poly::input(istream & in){
	in>>degree;
	for (int i=0; i<degree+1; i++) {
		in>>coefs[i];
	}
}
int Poly::evaluate(int x){
	int sum=0;
	double xd = static_cast<double>(x);
	double totalPow;
	for (int i=0; i<degree+1; i++) {
		totalPow =pow(xd, i);
		sum+=(coefs[i]*totalPow);
	}
	return sum;
	
}
Poly Poly:: operator+(const Poly& p)
{
	Poly temp;//declare to hold new result
	if (degree < p.degree) {
		degree=p.degree;
	}
	for (int i=0; i<degree+1; i++){
	temp.coefs[i] =coefs[i] + p.coefs[i];
	}
	temp.degree = degree;
	return temp;
	
}
Poly Poly:: operator*(const Poly& p)
{
	
	Poly temp;//declare to hold new result
	for (int i=0; i<degree+1; i++){
		temp.coefs[i] =coefs[i] * p.coefs[i];//I don't know what to do here to add the exponents of the coefficients.  This is also where I get zero after the shorter polynomial ends.
	}
		temp.degree = degree;
	return temp;
}
istream & operator>>(istream & in, Poly &p){
	p.input(in);
	return in;
}
ostream &operator<<(ostream &out, const Poly &p){
	p.display(out);
	return out;
}

#include <iostream>
#include "Poly.h"
using namespace std;

int main () {
	Poly p1, p2, p3, p4;
	int x;
    cout << "Please enter the number of degrees you want followed by the number of coefficints: ";
	cin>>p1;
	cout<<endl;
	cout << "Please do the same again: ";
	cin>>p2;
	cout << "P1 = "<<p1<<endl;
	cout << "What do you want x to be for P1: ";
	cin>>x;
	cout << "P1 ="<<p1.evaluate(x)<<endl;
	cout <<" P2 = "<<p2<<endl;
	p3=p1+p2;
	cout << "addition "<<p3<<endl;
	p4=p1 *p2;
	cout << "time "<<p4<<endl;
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.