C++ إثقال * بالنسبة متعدد الحدود الضرب
-
22-07-2019 - |
سؤال
لذا تم تطوير متعدد الحدود من الدرجة حيث مدخلات المستخدم:1 x^0 + 2x^1 + 3x^2...و 1,2,3 (معاملات) يتم تخزينها في الباحث مجموعة
بلدي زائد + و - مهام العمل ، ومع ذلك ، * لا يعمل.بغض النظر عن الإدخال, لكنه يظهر دائما -842150450
متى يجب أن تكون (5x^0 + x^1) * (-3x^0 + x^1) = -15x^0 + 2x^1 + 1 x^2
أو (x+5)(x-3) = x^2 +2x - 15
أنا باستخدام طاقتها * وظيفة مثل : Polynomial multiply = one * two;
Im التخمين المشكلة 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
المحلول
لا يبدو أن التهيئة على temp.coefficient[i+j]
إلى الصفر في operator * ()
.
temp.coefficient = new int [count];
std::memset (temp.coefficient, 0, count * sizeof(int));
نصائح أخرى
تحويل -842150450 إلى عرافة إلى العثور على واحد من السحر القيم المستخدمة في 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];
نقدم لك مجموعة من الأصفار ؟
وإلا في حلقة إضافة الأشياء إلى القمامة.
محل
temp.coefficient = new int [count];
قبل
temp.coefficient = new int [count]();
بغية صفر-تهيئة مجموعة القيم.