c ++初学者 - 课程和传递

时间:2011-11-30 05:27:54

标签: c++ class

我正在尝试打印这些多项式,但我似乎无法打印出我想要的内容。 如果我的多项式为1*x + 2*x^2,则输出为4*x。我想要1 + 4*x

void Poly :: derivative (){
  term *z ;
  if ( term_t == NULL)
    return ;
  term *temp1;
  temp1 = term_t;
  while ( temp1 != NULL ){
   if ( term_t == NULL ){
     term_t = new term ;
      z = term_t ;
    }
    else{
      z -> next = new term ;
      z = z -> next ;
    }
    z-> coef = temp1 -> coef * temp1 -> exp;
    z-> exp = temp1 -> exp - 1;
    temp1 = temp1 -> next;
  }
  term_t=z;
}

我有一个课程poly和一个结构term_t,其中包含coefexp

1 个答案:

答案 0 :(得分:0)

就个人而言,我有衍生函数返回Poly,而不是修改现有函数。像这样的东西

Poly derivative() {
    Poly res;
    Term *temp1 = this->term_t;
    while (temp1 != NULL) {
      int nexp = temp1->getExp() - 1;
      int ncoef = temp1->getCoef() * temp1->getExp();
      res.add(new Term(ncoef, nexp));
      temp1 = temp1->getNext();
    }
    return res;
}

至于打印问题,是的,你没有提供足够的代码来真正知道发生了什么。所以,我自己写了......这就是我解决问题的方法。首先是像这样的Term类

class Term {
public:
  Term(int coef, int exp) {
    this->coef = coef;
    this->exp = exp;
    this->next = NULL;
  }

  std::string toString() const {
    std::stringstream ss;
    if (this->coef == 0) return "0";
    if (this->exp == 0) ss << this->coef;
    else {
      if (this->coef != 1) ss << this->coef;
      ss << "x";
      if (this->exp != 1) ss << "^" << this->exp;
    }
    return ss.str();
  }

  int getCoef() const {return this->coef;}
  int getExp() const {return this->exp;}
  Term* getNext() const {return this->next;}
  void setNext(Term* n) {this->next = n;}

private:
  int coef;
  int exp;
  Term* next;
};

然后是像这样的Poly类

class Poly {
public:
  Poly() {
    this->term_t = NULL;
  }
  void add(Term* nt) {
    if (this->term_t == NULL) {
      this->term_t = nt;
    } else {
      Term* t = this->term_t;
      while(t->getNext() != NULL) t = t->getNext();
      t->setNext(nt);
    }
  }
  std::string toString() const {
    std::stringstream ss;
    Term* t = this->term_t;
    while (t != NULL) {
      ss << t->toString();
      if (t->getNext() != NULL) ss << " + ";
      t = t->getNext();
    }
    return ss.str();
  }

  Poly derivative() {
    Poly res;
    Term *temp1 = this->term_t;
    while (temp1 != NULL){
      int nexp = temp1->getExp() - 1;
      int ncoef = temp1->getCoef() * temp1->getExp();
      res.add(new Term(ncoef, nexp));
      temp1 = temp1->getNext();
    }
    return res;
  }

private :
  Term* term_t;
};

将Term对象的内存管理留给类用户,但您也可以为Poly类编写一个删除它们的析构函数。