【发布时间】:2015-11-20 14:48:53
【问题描述】:
我希望这段代码有意义.....我创建了两个多项式并尝试将它们相乘。问题是我不知道我应该怎么做才能正确地将它们相乘。该程序将多项式相乘,将结果存储到另一个多项式,但它不会将具有相同幂的系数相加。
我应该怎么做才能做到这一点?另外我应该如何在这个程序中使用
free()?
#include <stdio.h>
#include <stdlib.h>
typedef struct poly {
int coef;
int exp;
struct poly *next;
} poly;
int main(void) {
poly * po1, *head, *po2, *head2, *po3, *head3 = NULL;
int sel, c = 1;
head = NULL;
printf(
"\nInsert elements for the first polynomial from the biggest to the smallest power of x. (Enter a power of zero (0) to stop)\n");
while (1) {
po1 = (poly *) malloc(sizeof(poly));
printf("Give number: ");
scanf("%d", &po1->coef);
printf("Give power of x: ");
scanf("%d", &po1->exp);
po1->next = head;
head = po1;
if (po1->exp == 0) break;
}
head2 = NULL;
printf(
"\nInsert elements for the second polynomial from the biggest to the smallest power of x. (Enter a power of zero (0) to stop)\n");
while (1) {
po2 = (poly *) malloc(sizeof(poly));
printf("Give number: ");
scanf("%d", &po2->coef);
printf("Give power of x: ");
scanf("%d", &po2->exp);
po2->next = head2;
head2 = po2;
if (po2->exp == 0) break;
}
po1 = head;
po2 = head2;
printf("Multiplying********\n");
po1 = head;
po2 = head2;
while (po1 || po2) {
po2 = head2;
while (po1 && po2) {
po3 = (poly *) malloc(sizeof(poly));
po3->coef = (po1->coef) * (po2->coef);
po3->exp = (po1->exp) + (po2->exp);
po3->next = head3;
head3 = po3;
po2 = po2->next;
}
po1 = po1->next;
}
while (po3) {
printf("%+d(x^%d)", po3->coef, po3->exp);
po3 = po3->next;
}
printf("\n");
}
}
【问题讨论】:
-
这里肯定有一些缺失的代码。请编辑您的问题,使其显示您的所有代码,并且格式正确。
-
如果您将系数存储在数组中,您将有一个非常更轻松的时间,这样数组位置代表相应的指数(例如,
3x^2 + 2x - 1将表示为 @ 987654325@)。您的产品将在嵌套循环中计算为r[i+j] += x[i] * y[j]。
标签: c