C++重载*用于多项式乘法

Rap*_*rex 1 c++ polynomial-math

所以我一直在开发一个用户输入的多项式类: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),因为它使用了一个long int,但是,加法和减法完美地工作

我的构造函数

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++;
    }
}
Run Code Online (Sandbox Code Playgroud)

和重载*功能

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;
}
Run Code Online (Sandbox Code Playgroud)

继承了我的整个代码:http://pastie.org/721143

dav*_*420 7

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

temp.coefficient = new int [count];
std::memset (temp.coefficient, 0, count * sizeof(int));
Run Code Online (Sandbox Code Playgroud)


Han*_*ant 5

将-842150450转换为十六进制,以找回调试版本中CRT中使用的一个神奇值.这有助于在代码中找到错误:

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

还有很多其他bugz btw,祝你好运.