所以我一直在开发一个多项式类,其中用户输入:1x^0 + 2x^1 + 3x^2... 和 1,2,3(系数)存储在 int 数组中
我重载的 + 和 - 函数可以工作,但是 * 不起作用。无论输入如何,它总是显示 -842150450
什么时候应该是 (5x^0 + x^1) * (-3x^0 + x^1) = -15x^0 + 2x^1 + 1x^2
或 (x +5)(x-3) = x^2 +2x - 15
我正在使用重载的 * 函数,例如:Polynomial multiply = one * two;
我猜问题是 strtol(p, &endptr, 10) 因为它使用长整数,但是,加法和减法效果很好
我的构造函数
Polynomial::Polynomial(char *s)
{
char *string;
string = new char [strlen(s) + 1];
int length = strlen(string);
strcpy(string, s);
char *copy;
copy = new char [length];
strcpy(copy, string);
char *p = strtok(string, " +-");
counter = 0;
while (p)
{
p = strtok(NULL, " +-");
counter++;
}
coefficient = new int[counter];
p = strtok(copy, " +");
int a = 0;
while (p)
{
long int coeff;
char *endptr;
coeff = strtol(p, &endptr, 10); //stops at first non number
if (*p == 'x')
coeff = 1;
coefficient[a] = coeff;
p = strtok(NULL, " +");
a++;
}
}
和重载的 * 函数
Polynomial Polynomial::operator * (const Polynomial &right)
{
Polynomial temp;
//make coefficient array
int count = (counter + right.counter) - 1;
temp.counter = count;
temp.coefficient = new int [count];
for (int i = 0; i < counter; i++)
{
for (int j = 0; j < right.counter; j++)
temp.coefficient[i+j] += coefficient[i] * right.coefficient[j];
}
return temp;
}
这是我的整个代码: http: //pastie.org/721143