所以我一直在开发一个多项式类,其中用户输入:1x^0 + 2x^1 + 3x^2 ...和1,2,3(系数)存储在int arrayC++过载*多项式乘法
但是,我的重载的+和 - 函数工作不起作用。无论输入如何,它始终显示-842150450
何时应该是(5x^0 + x^1)*(-3x^0 + x^1)= -15x^0 + 2x^1 + 1x^2
或(x + 5)(X-3)= X^2 + 2× - 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
问题是?.. – 2009-12-01 00:49:48
我的重载的+和 - 函数工作,但是,重载*不起作用。无论输入什么,它总是显示-842150450 – Raptrex 2009-12-01 00:51:08
我从pastie.org下载了你的代码,用g ++ 4.4.1编译它,它运行得很好。需要一些错误检查。 – divegeek 2009-12-01 00:57:58