Pergunta

Então, eu tenho vindo a desenvolver uma classe polinomial onde um usuário entradas: 1x ^ 0 + 2x ^ 1 + 3x ^ 2 ... e 1,2,3 (os coeficientes) são armazenados em uma matriz int

Meu sobrecarregados + e - funções de trabalho, no entanto, * não funciona. Não importa a entrada, ele sempre mostra -842150450
quando é deve ser (5x ^ 0 + x ^ 1) * (-3x ^ 0 + x ^ 1) = -15x ^ 0 + 2x ^ 1 + 1x ^ 2
ou (x + 5) (X-3) = x ^ 2 + 2x - 15

Eu estou usando a função * sobrecarregado como: Polynomial multiply = one * two;
Im adivinhar o problema é strtol (p, & endptr, 10), uma vez que utiliza um long int, no entanto, adição e subtração funciona perfeitamente

Meu construtor

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++;
    }
}

e a função sobrecarregada *

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;
}

E aqui está todo o meu código: http://pastie.org/721143

Foi útil?

Solução

Você não aparecem para inicializar o temp.coefficient[i+j] a zero em sua operator * ().

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

Outras dicas

Convert -842150450 para hex encontrar para trás uma das valores mágicos usado no CRT na compilação de depuração. Que ajuda a encontrar o bug em seu código:

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

Existem muitas outras bugz btw, boa sorte corrigi-los.

O

temp.coefficient = new int [count];

dar-lhe uma série de zeros?

Caso contrário, em seu loop for que você está adicionando coisas para lixo.

Substitua

temp.coefficient = new int [count];

por

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

a fim de zero-inicializar os valores da matriz.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top