0

A polynomial class is implemented, with 2 D array of terms, and number of terms as data members. array rows are coefficients and array columns are exponents. we aim to overload + operator to do addition i.e. add coefficients if exponents are same, else include terms as is.

The output is correct partially, last term of output is incorrect..please look into operator + overloading and suggest remedy ! Thanks in advance...

see comments for removal of previous flaws.

#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H

#include <iostream>
using namespace std;
#define MAX 10

class Polynomial {
      public :
             Polynomial ();
             //~Polynomial(){ delete [] terms[MAX]; }  (see comments)
             void enterTerms();
             Polynomial operator +(const Polynomial & );
      private :
             int terms[MAX][2]; //define size statically if not using "new"
             int n; //number of terms
};        
#endif

#include "polynomial.h" 


 Polynomial Polynomial :: operator + ( const Polynomial & p ){
           Polynomial temp, sum;
           temp.n = n + p.n;
           int common = 0;
           //first write sum as concatenation of p1 and p2               
           for ( int i = 0 ; i < n ; i++ ){ 
                   temp.terms[i][0] = terms[i][0];
                   temp.terms[i][1] = terms[i][1];
           }
           //notice j and k for traversing second half of sum, and whole p2 resp
           for ( int j = n, k = 0; j < n + p.n, k < p.n ; j++, k++ ){  
                   temp.terms[j][0] = p.terms[k][0];
                   temp.terms[j][1] = p.terms[k][1];
           }
           for ( int l = 0; l < temp.n - 1 ; l++ ){ // 0 to 1 less than length
               for ( int m = l + 1 ; m < temp.n ; m++ ){ // 1 more than l to length,so that compared pairs are non redundant
                   if( temp.terms[l][1] == temp.terms[m][1] ){
                           common++;   //common terms reduce no. of terms
                           temp.terms[l][0] +=  temp.terms[m][0]; //coefficients added of exponents same
                           temp.terms[m][0] = 0;                
                   }  
               }
           }                 
           sum.n = temp.n - common;
           for ( int q = 0, r = 0; q < temp.n, r < sum.n; q++, r++){
                    if ( temp.terms[q][0] == 0 )
                       continue;
                    else if ( temp.terms[q][0] != 0 ){
                           sum.terms[r][0] = temp.terms[q][0];
                           sum.terms[r][1] = temp.terms[q][1];
                    }
           }      
           cout << sum;
           return sum;
}   

   Polynomial :: Polynomial(){
         for ( int i = 0; i < MAX; i++ ){
             terms[i][0] = 0;
             terms[i][1] = 0;  
         }           
}       
void Polynomial :: enterTerms(){
      int num;
      cout<<"enter number of terms in polynomial\n";
      cin >> num;
      n = num >= 0 ? num : 1;
      cout << "enter coefficient followed by exponent for each term in polynomial\n";
      for ( int i = 0; i < n ; i++)  
              cin >> terms[i][0] >> terms[i][1] ;
}
   int main(){
    Polynomial p1 , p2;
    p1.enterTerms();
    p2.enterTerms();
    p1 + p2;  
    system("PAUSE");
    return EXIT_SUCCESS;
}

op

4

3 回答 3

1

用最大的元素声明你的数组:

private :
         int terms[MAX][2]; 
于 2013-06-18T11:22:15.380 回答
0
#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H

#include <iostream>
using namespace std;

#define MAX 10

class Polynomial {
      friend ostream &operator<< (ostream &, const Polynomial &);
      public :
             Polynomial ();
             void enterTerms();
             Polynomial operator +(const Polynomial & );
      private :
             int terms[MAX][2]; //either static size(MAX rows) or use "new" for dynamic allocation
             int n; //number of terms
};             

#endif

#include "polynomial.h"

ostream &operator<< (ostream & out, const Polynomial & p){
        for ( int i = 0 ; i < p.n ; i++ ){
            if ( i == p.n - 1 )//last term does not have + appended
                  out << p.terms[i][0] <<"x^"<<p.terms[i][1]<<endl;
            else
                  out << p.terms[i][0]<<"x^"<<p.terms[i][1]<<" + ";
        }
        return out;
}
Polynomial :: Polynomial(){
         for ( int i = 0; i < MAX; i++ ){
             terms[i][0] = 0;
             terms[i][1] = 0;  
         }           
}       
void Polynomial :: enterTerms(){//enterTerms() not in constructor so that no prompt for entering 
//terms while doing + - etc., they also produce Poylnomial instance (i.e. invoke constructor)
      int num;
      cout<<"enter number of terms in polynomial\n";
      cin >> num;
      n = num >= 0 ? num : 1;
      cout << "enter coefficient followed by exponent for each term in polynomial\n";
      for ( int i = 0; i < n ; i++)  
              cin >> terms[i][0] >> terms[i][1] ;
}
Polynomial Polynomial :: operator + ( const Polynomial & p ){
           Polynomial temp, sum;
           temp.n = n + p.n;
           int common = 0;

          // first write sum as concatenation of p1 and p2               
           for ( int i = 0 ; i < n ; i++ ){ 
                   temp.terms[i][0] = terms[i][0];
                   temp.terms[i][1] = terms[i][1];
           }
           //notice j and k for traversing second half of sum, and whole p2 resp
           for ( int j = n, k = 0; j < n + p.n, k < p.n ; j++, k++ ){  
                   temp.terms[j][0] = p.terms[k][0];
                   temp.terms[j][1] = p.terms[k][1];
           }
           for ( int l = 0; l < temp.n - 1 ; l++ ){ // 0 to 1 less than length
               for ( int m = l + 1 ; m < temp.n ; m++ ){ // 1 more than l to length,so that compared pairs are non redundant
                   if( temp.terms[l][1] == temp.terms[m][1] ){
                           common++;   //common terms reduce no. of terms in sum (see sum.n decl)
                           temp.terms[l][0] +=  temp.terms[m][0]; //coefficients added if exponents same
                           temp.terms[m][0] = 0;                
                   }  
               }
           } 
           sum.n = temp.n - common;  //if you place it above, common taken as 0 and sum.n is same as temp.n (logical error)         

           //just to debug, print temporary array
           cout << endl << temp;  

           for ( int q = 0, r = 0; q < temp.n; q++ ){
                    if ( temp.terms[q][0] == 0 )
                       continue;
                    else{
                         sum.terms[r][0] = temp.terms[q][0];
                         sum.terms[r][1] = temp.terms[q][1];
                         r++;
                    }
           }

           cout << endl << sum;
           return sum;
}                    
int main(){
    Polynomial p1 , p2;
    p1.enterTerms();
    p2.enterTerms();
    p1 + p2;  
    system("PAUSE");
    return EXIT_SUCCESS;
}

操作

于 2013-06-19T10:05:29.610 回答
0

虽然我知道您的“问题”已通过接受的答案解决,但我是否可以说,当您在标准库中拥有正确的数据结构时,C++ 中的指针和数组被忽略了,而不会浪费额外的资源或使用它们的表现。对于多项式类,我相信地图会做,并且当您有孔,即度数为 0 时,您不会像在数组实现中那样浪费空间;另外不用担心分配、释放和泄漏内存。我建议您至少考虑一次以下实现。我向你保证,这可以进一步改进很多。

#include <iostream>
#include <map>

using namespace std;

class Polynomial
{
public:
    int& coefficient(unsigned degree)
    {
        return deg2coeff[degree];
    }

    const int& coefficient(unsigned degree) const
    {
        return deg2coeff.at(degree);
    }

    size_t size() const
    {
        return deg2coeff.size();
    }

    Polynomial operator+(const Polynomial &that)
    {
        Polynomial result;
        result.deg2coeff = (this->size() > that.size()) ? deg2coeff : that.deg2coeff;
        const auto &smaller = (this->size() <= that.size()) ? *this : that;
        for (const auto &it : smaller.deg2coeff)
        {
            result.coefficient(it.first) += smaller.coefficient(it.first);
        }
        return result;
    }

    friend std::ostream& operator<<(std::ostream& ostr, const Polynomial &poly);

private:
    map<unsigned, int> deg2coeff;
};

std::ostream& operator<<(std::ostream& ostr, const Polynomial &poly)
{
    for (auto it = poly.deg2coeff.crbegin(); it != poly.deg2coeff.crend(); ++it)
    {
        if (it->second == -1)
            ostr << '-';
        else if (it->first == 0 || it->second != 1)
        {
            if (it->second > 0)
                ostr << "+";
            ostr << it->second;
        }

        if (it->first)
        {
            ostr << "x";
            if (it->first != 1)
                ostr << "^" << it->first;
        }
    }
    return ostr<<endl;
}

void read_polynomial(Polynomial &poly)
{
    cout << "Number of degrees: ";
    unsigned n;
    cin >> n;
    int degree, coeff;
    for (unsigned i = 0; i < n; ++i)
    {
        cout << "Enter Degree, Coefficient: ";
        cin >> degree >> coeff;
        if (coeff)
        {
            poly.coefficient(degree) = coeff;
        }
    }
}

int main()
{
    Polynomial p1;
    read_polynomial(p1);
    cout << p1;

    Polynomial p2;
    read_polynomial(p2);
    cout << p2;

    cout << (p1 + p2);
}

输出

Number of degrees: 4
Enter Degree, Coefficient: 9 2
Enter Degree, Coefficient: 3 -12
Enter Degree, Coefficient: 1 3
Enter Degree, Coefficient: 0 -27
+2x^9-12x^3+3x-27
Number of degrees: 2
Enter Degree, Coefficient: 13 10
Enter Degree, Coefficient: 11 34
+10x^13+34x^11
+10x^13+34x^11+2x^9-12x^3+3x-27
于 2013-06-18T12:17:33.173 回答