Wednesday, 15 September 2010

C++ polynomial class, print member function not working well with the power -



C++ polynomial class, print member function not working well with the power -

i'm making polynomial class basic operations on 2 polynomials. other fellow member functions work except print function. here print fellow member function:

void polynomial::print() const { string plus;//plus plus sign in front end of every element except first element plus="+"; int k=0;//k powerfulness of each element in polynomial if(coefficient[0]!=0) cout<<coefficient[0]; for(int i=1;i<coefficient.size();i++) { if(coefficient[i]==-1234) break; if(coefficient[i]==0) { k++; } else if(coefficient[i]==1) { if(coefficient[i]>=1) cout<<plus; cout<<"x"; k++; } else if(coefficient[i]==-1) { if(coefficient[i]>=1) cout<<plus; cout<<"-x"; k++; } else { if(coefficient[i]>=1) cout<<plus; cout<<coefficient[i]<<"x"; if(coefficient[i]!=-1234) { k++; } else break; if(k>1) { cout<<"^"<<k; } } } cout<<endl; return; }

now if user inputs: 1 2 3 1 polynomial prints : 1+2x+3x^2+x 4th term in polynomial not have correspond k (power) of 4. i've been checkin code hours...still don't know goes wrong. help!!!

your loop should this. not printing powerfulness when coefficient 1 or -1:

for(int i=1;i<coefficient.size();i++) { if(coefficient[i]==-1234) break; if(coefficient[i]==0) { k++; } else if(coefficient[i]==1) { if(coefficient[i]>=1) cout<<plus; cout<<"x"; k++; if(k>1) { cout<<"^"<<k; } } else if(coefficient[i]==-1) { if(coefficient[i]>=1) cout<<plus; cout<<"-x"; k++; if(k>1) { cout<<"^"<<k; } } else { if(coefficient[i]>=1) cout<<plus; cout<<coefficient[i]<<"x"; if(coefficient[i]!=-1234) { k++; } else break; if(k>1) { cout<<"^"<<k; } } }

c++

No comments:

Post a Comment