質問

したがって、ユーザーが入力する多項式クラスを開発しています: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

次のようなオーバーロードされた*関数を使用しています:多項式の乗算= 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++;
    }
}

およびオーバーロードされた*関数

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

役に立ちましたか?

解決

operator *() temp.coefficient [i + j] をゼロに初期化するようには見えません。

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

他のヒント

-842150450を16進数に変換して、マジック値の1つを見つけるデバッグビルドのCRTで使用されます。それはあなたのコードのバグを見つけるのに役立ちます:

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

他にも多くのバグがありますが、それらを修正することは幸運です。

する

temp.coefficient = new int [count];

ゼロの配列を教えてください

それ以外の場合、forループでごみにデータを追加しています。

交換

temp.coefficient = new int [count];

by

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

配列値をゼロで初期化するため。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top