2011-11-30 76 views
0

我想打印這些多項式,但我似乎無法打印我想要的。 如果我的多項式是1*x + 2*x^2那麼輸出將是4*x。我想要1 + 4*xC++初學者 - 類和傳遞

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_tcoef和他們exp

+2

您的Poly :: derivative()方法與打印poly有什麼關係?你提出的代碼片段與你的問題沒有任何關係。 – greatwolf

回答

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; 
} 

至於雖然打印問題,是啊,你有沒有提供了足夠的代碼的真正瞭解發生了什麼事情。所以,我寫了自己的...這是我如何處理這個問題。首先這樣

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; 
}; 

然後聚類這樣

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; 
}; 

一個期限類會離開期限的內存管理對象到用戶類,但你也可以編寫一個析構函數對於刪除它們的Poly類。