문제
그래서 나는 사용자가 입력하는 다항식 클래스를 개발하고 있습니다 : 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)이라고 추측하지만 긴 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
해결책
당신은 초기화하는 것처럼 보이지 않습니다 temp.coefficient[i+j]
당신의 0에 operator * ()
.
temp.coefficient = new int [count];
std::memset (temp.coefficient, 0, count * sizeof(int));
다른 팁
-842150450을 16 진로 변환하여 마법 가치 디버그 빌드에서 CRT에 사용됩니다. 코드에서 버그를 찾는 데 도움이됩니다.
temp.coefficient = new int [count];
// Must initialize the memory
for (int ix = 0; ix < count; ++ix) temp.coefficient[ix] = 0;
다른 Bugz BTW가 많이 있습니다. 행운을 빕니다.
하다
temp.coefficient = new int [count];
제로 배열을 줘?
그렇지 않으면 루프를 위해 쓰레기에 물건을 추가합니다.
바꾸다
temp.coefficient = new int [count];
~에 의해
temp.coefficient = new int [count]();
배열 값을 제로 이니티얼로 만들기 위해.
제휴하지 않습니다 StackOverflow