Пример #1
0
/***********************************************************************
* overloaded << operator that outputs the polynomial in the proper format
***********************************************************************/
ostream& operator << (ostream& outFile, Poly& op1)
{
   Term temp;
   int size = op1.getNumTerms();

   for (int i = 0; i < size; i++)
   {       
      temp = op1.getTerm(i);

      // handle addition and substraction symbols
      if (i > 0 && temp.getCoeff() > 0)
         outFile << " + ";
      else if (i > 0)
         outFile << " - ";

      // handle displaying coeffecients
      if (temp.getCoeff() > 1 || i == 0)
         outFile << temp.getCoeff();
      else
         outFile << -1 * temp.getCoeff();     

      // handle displaying exponents
      if (temp.getExpon() > 1)
         outFile << "x^" << temp.getExpon();
      else if (temp.getExpon() == 1)
         outFile << "x";
   }

   return (outFile);
}
Пример #2
0
/***********************************************************************
* Inserts a term into a polynomial in the proper location.  If a term
* is inserted with a duplicate exponent, the terms are combined.  If any
* coefficient goes to zero that term is removed from the polynomial.
***********************************************************************/
void Poly::insertTerm(Term t)
{
   float sum = 0;
   Term temp;

   // if the list is not full
   if (numTerms < maxItems && t.getCoeff() != 0)
   {
      for (int i = 0; i < numTerms; i++)
      {
         // find duplicate exponent
         if (t.getExpon() == terms[i].getExpon())
         {
            //combine terms
            sum = t.getCoeff() + terms[i].getCoeff();
            if (sum == 0)
            {
               for (int j = i; j < numTerms-j; j++)
               {
                  terms[j] = terms[j+1];                  
               }
               numTerms--;
            }
            else 
               terms[i].setCoeff(sum);
            return;
         }
         else if (t.getExpon() > terms[i].getExpon())
         {
            temp = terms[i];
            terms[i] = t;
            //recursive function call
            insertTerm(temp);
            return;
         }
      }
      terms[numTerms++] = t;
   }
}