c++ 多项式 Polynomial#include using namespace std;struct Polynomial {int degree;int *coeffs; // array of coefficients from // lowest degree to highest degree};// reads the coefficients of a polynomial from standard input and // creates a polynomia
来源:学生作业帮助网 编辑:六六作业网 时间:2025/01/09 17:40:52
c++ 多项式 Polynomial#include using namespace std;struct Polynomial {int degree;int *coeffs; // array of coefficients from // lowest degree to highest degree};// reads the coefficients of a polynomial from standard input and // creates a polynomia
c++ 多项式 Polynomial
#include
using namespace std;
struct Polynomial {
int degree;
int *coeffs; // array of coefficients from
// lowest degree to highest degree
};
// reads the coefficients of a polynomial from standard input and
// creates a polynomial which it returns
Polynomial* readPoly();
// outputs a polynomial to standard output using the variable x
void outputPoly( Polynomial* p,char x );
// computes the sum of two polynomials
Polynomial* addPoly( Polynomial* a,Polynomial* b );
// computes the product of two polynomials
Polynomial* multPoly( Polynomial* a,Polynomial* b );
int main()
{
char x;
Polynomial *p;
readPoly();
outputPoly(p,x);
return 0;
}
Polynomial* readPoly()
{
int deg,*coefficient;
coutdeg;
coefficient = new int[deg+1]; // space for deg+1 coefficient
cout degree = deg;
p -> coeffs = coefficient;
}
//if the last degree is associated with a zero ,the output will show an extra "+" sign in the end
void outputPoly(Polynomial* p,char x)
{
x = 'x';
//char sign = '+';
for(int i= 0;idegree;i++){
string sign = "+";
if(p->coeffs[i] == 0)
{
continue;
}
if(i == 0)
{
if((p->coeffs[i+1]degree))
sign = "";
coutcoeffs[i]degree)) //if it is the last coefficent with number
sign = "";
cout
c++ 多项式 Polynomial#include using namespace std;struct Polynomial {int degree;int *coeffs; // array of coefficients from // lowest degree to highest degree};// reads the coefficients of a polynomial from standard input and // creates a polynomia
有个大问题:主函数里面的指针p,与Polynomial* readPoly()中的p,属于不同的作用域.两个是不同的两个指针变量.所以你在readPoly()当中创建了的多项式结构并没有赋给主函数里面的p,这时p所指向的内存是未知的,可能引起系统报错.
改法:
1.readPoly()最后加一个 return p...
主函数里面 p = readPoly();
2.由于用了动态分配,最后应该释放掉好像是用delete吧,在主函数最后把原先用new分配的指针所指向的空间都释放了.
3.输出也有问题:好像不能输出负系数的?比如"x^3 - x^2"...
大概就发现了这几个问题,你改了看下还有错误的话再说吧.