2009-12-01 106 views
1

所以我一直在开发一个多项式类,其中用户输入: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

+0

问题是?.. – 2009-12-01 00:49:48

+0

我的重载的+和 - 函数工作,但是,重载*不起作用。无论输入什么,它总是显示-842150450 – Raptrex 2009-12-01 00:51:08

+1

我从pastie.org下载了你的代码,用g ++ 4.4.1编译它,它运行得很好。需要一些错误检查。 – divegeek 2009-12-01 00:57:58

回答

7

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

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

在一个语句中执行此操作的更简单的方法是'new int [count]()',它将默认初始化每个元素。 – 2009-12-01 01:06:55

+0

谢谢,这解决了它。为什么我必须添加std:memset ... – Raptrex 2009-12-01 01:07:30

+0

请看我的回答,即使使用此修复程序,您的代码也不安全,无处不在。 – Earlz 2009-12-01 01:07:58

1

是否

temp.coefficient = new int [count]; 

给你零的数组?

否则,在for循环中,您正在向垃圾中添加东西。

5

将-842150450转换为十六进制表示在调试版本中找回在CRT中使用的magic values之一。这有助于找到您的代码中的错误:

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

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

+0

尼斯链接。 +1为你 – 2009-12-01 01:17:34

+1

这是一个非常低效的初始化数组的方式。用'memset'代替,或者在'new []'中使用明确的初始值设定项。 – 2009-12-01 01:23:06

+0

查看发布版本中为此循环生成的代码。 – 2009-12-01 02:10:12

1

为了更换

temp.coefficient = new int [count]; 

通过

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

到零初始化数组的值。