[英]c++ beginner - class and passing
I am trying to print these polynomials but I can not seem to print what I want. 我正在尝试打印这些多项式,但是我似乎无法打印我想要的东西。 If my polynomial was
1*x + 2*x^2
then output would be 4*x
. 如果我的多项式是
1*x + 2*x^2
那么输出将是4*x
。 I want 1 + 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;
}
I have a class poly
and a struct term_t
with coef
and exp
in them. 我有一个类
poly
和带有coef
和exp
的结构term_t
。
Personally, I'd have the derivative function return a Poly, rather than modify the existing one. 就个人而言,我希望派生函数返回Poly,而不是修改现有的Poly。 Something like this
像这样
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;
}
As for the printing problem though, yeah, you haven't provided enough of your code to really know what's going on. 但是对于打印问题,是的,您没有提供足够的代码来真正了解正在发生的事情。 So, I wrote my own... this is how I'd approach the problem.
所以,我写了自己的书……这就是解决问题的方式。 First a Term class like this
首先是这样的术语类
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;
};
then a Poly class like this 然后像这样的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;
};
That'd leave the memory management of the Term objects up to the class users, but you could also write a destructor for the Poly class that deletes them. 这样可以将Term对象的内存管理权交给类用户,但是您也可以为Poly类编写一个析构函数,以将其删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.