Nov 30, 2012 at 2:41pm UTC
Hello all,
I have been working on a program and had some help.
I dont understand some of the coding now.
The use of -1 -1 to exit seems to be the only thing that will work with the code but can it be changed to something else like the word "exit"?
here is the code...
#include <iostream>
using namespace std;
class polynomial
{
private:
int coeff[10];
int exp[10];
int terms;
public: polynomial();
void input(int);
void output();
polynomial operator + (polynomial);
polynomial operator - (polynomial);
};
int main()
{
int i,
int na,
int nb,
int nc;
polynomial a,b,c;
a.input(1);
b.input(2);
cout<<"\n\n ";
a.output();
cout<<" + ";
b.output();
cout<<"\n ";
c=a+b;
c.output();
cout<<endl;
cout<<"\n\n ";
a.output();
cout<<" - ";
b.output();
cout<<"\n ";
c=a-b;
c.output();
cout<<endl;
system("pause");
return 0;
}
polynomial::polynomial()
{int i;
for(i=0;i<10;i++)
{coeff[i]=0;
exp[i]=0;
}
terms=0;
}
void polynomial:: input(int poly)
{
cout<<"Input is in the form coefficient space exponent\n -1 -1 to exit\n"; // This is what I'd like to play around with
cout<<"Enter polynomial number "<<poly<<endl;
cin>>coeff[terms]>>exp[terms];
while(coeff[terms]>0||exp[terms]>=0)
{
terms++;
cin>>coeff[terms]>>exp[terms];
}
terms--;
}
void polynomial ::output()
{
int i;
for(i=0;i<terms;i++)
{
cout<<coeff[i]<<"x^"<<exp[i];
if(exp[i+1]>=0)
cout<<"+";
}
cout<<coeff[terms];
if(exp[terms]>1)
cout<<"x^"<<exp[terms];
cout<<endl<<endl;
}
polynomial polynomial :: operator + (polynomial b)
{int i=0,j=0,k=-1;
polynomial c;
c.terms=0;
do
{k++;
if(exp[i]>b.exp[j])
{c.exp[k]=exp[i];
c.coeff[k]=coeff[i];
i++;
}
else
if(b.exp[j]>exp[i])
{c.exp[k]=b.exp[j];
c.coeff[k]=b.coeff[j];
j++;
}
else
{c.exp[k]=b.exp[i];
c.coeff[k]=coeff[i]+b.coeff[j];
i++;
j++;
}
}while(c.exp[k]>=0);
c.terms=k-1;
return c;
}
polynomial polynomial:: operator -(polynomial b)
{int i=0,j=0,k=-1;
polynomial c;
c.terms=0;
do
{k++;
if(exp[i]>b.exp[j])
{c.exp[k]=exp[i];
c.coeff[k]=coeff[i];
i++;
}
else
if(
b.exp[j]>exp[i])
{
c.exp[k]=b.exp[j];
c.coeff[k]=b.coeff[j]*-1;
j++;
}
else
{
c.exp[k]=b.exp[i];
c.coeff[k]=coeff[i]-b.coeff[j];
i++;
j++;
}
}
while(c.exp[k]>=0);
c.terms=k-1;
return c;
}