因此,我已经开发一个多项式类,其中用户输入:1X ^ 0 + 2×^ 1 + 3×^ 2 ...和1,2,3-(系数)被存储在一个int数组

我的重载+和 - 功能工作,但是,*不工作。无论输入,它总是显示-842150450结果 当是应该是(5×^ 0 + X ^ 1)*(-3x ^ 0 +的x ^ 1)= <强> -15x ^ 0 + 2×^ 1 + 1×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

有帮助吗?

解决方案

您似乎没有初始化temp.coefficient[i+j]为零你operator * ()

temp.coefficient = new int [count];
std::memset (temp.coefficient, 0, count * sizeof(int));

其他提示

转换-842150450为十六进制找回的魔值之一在调试版本的CRT使用。这有助于发现的bug在你的代码:

    temp.coefficient = new int [count];
    // Must initialize the memory
    for (int ix = 0; ix < count; ++ix) temp.coefficient[ix] = 0;

有很多其他的bugz顺便说一句,好运将它们固定。

确实

temp.coefficient = new int [count];

给你零的阵列

否则,在你的循环中,您要添加的东西垃圾。

替换

temp.coefficient = new int [count];

通过

temp.coefficient = new int [count]();

以零初始化数组的值。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top