请用C语言帮我写一段代码,设计函数分别求两个一元多项式的乘积与和。 输入格式: 输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。 数字间以空格分隔。 输出格式: 输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。 数字间以空格分隔,但结尾不能有多余空格。 零多项式应输出。0 0 输入样例: 4 3 4 -5 2 6 1 -2 0 3 5 20 -7 4 3 1 输出样例: 15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1 5 20 -4 4 -5 2 9 1 -2 0
时间: 2024-01-01 09:03:58 浏览: 106
请参考以下的 C 语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int coef;
int exp;
} Term;
Term* multiply_poly(Term poly1[], int n1, Term poly2[], int n2, int* pn3) {
int max_n = n1 * n2;
Term* res = (Term*) malloc(max_n * sizeof(Term));
int i, j, k = 0;
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
int coef = poly1[i].coef * poly2[j].coef;
int exp = poly1[i].exp + poly2[j].exp;
if (coef != 0) {
res[k].coef = coef;
res[k].exp = exp;
k++;
}
}
}
*pn3 = k;
return res;
}
Term* add_poly(Term poly1[], int n1, Term poly2[], int n2, int* pn3) {
int max_n = n1 + n2;
Term* res = (Term*) malloc(max_n * sizeof(Term));
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (poly1[i].exp == poly2[j].exp) {
int coef = poly1[i].coef + poly2[j].coef;
if (coef != 0) {
res[k].coef = coef;
res[k].exp = poly1[i].exp;
k++;
}
i++;
j++;
} else if (poly1[i].exp > poly2[j].exp) {
res[k].coef = poly1[i].coef;
res[k].exp = poly1[i].exp;
k++;
i++;
} else {
res[k].coef = poly2[j].coef;
res[k].exp = poly2[j].exp;
k++;
j++;
}
}
while (i < n1) {
res[k].coef = poly1[i].coef;
res[k].exp = poly1[i].exp;
k++;
i++;
}
while (j < n2) {
res[k].coef = poly2[j].coef;
res[k].exp = poly2[j].exp;
k++;
j++;
}
*pn3 = k;
return res;
}
int main() {
int n1, n2, n3;
scanf("%d", &n1);
Term* poly1 = (Term*) malloc(n1 * sizeof(Term));
int i;
for (i = 0; i < n1; i++) {
scanf("%d%d", &poly1[i].coef, &poly1[i].exp);
}
scanf("%d", &n2);
Term* poly2 = (Term*) malloc(n2 * sizeof(Term));
for (i = 0; i < n2; i++) {
scanf("%d%d", &poly2[i].coef, &poly2[i].exp);
}
// 计算乘积和和
Term* product = multiply_poly(poly1, n1, poly2, n2, &n3);
Term* sum_poly = add_poly(poly1, n1, poly2, n2, &n3);
// 输出乘积和和
if (n3 == 0) {
printf("0 0");
} else {
for (i = 0; i < n3; i++) {
printf("%d %d", product[i].coef, product[i].exp);
if (i < n3 - 1) {
printf(" ");
}
}
}
printf("\n");
if (n3 == 0) {
printf("0 0");
} else {
for (i = 0; i < n3; i++) {
printf("%d %d", sum_poly[i].coef, sum_poly[i].exp);
if (i < n3 - 1) {
printf(" ");
}
}
}
free(poly1);
free(poly2);
free(product);
free(sum_poly);
return 0;
}
```
这段代码中,`multiply_poly()` 函数用来计算两个一元多项式的乘积,`add_poly()` 函数用来计算两个一元多项式的和。输入部分读取两个多项式的系数和指数,输出部分先判断乘积和和是否为空,如果不为空则按指数递降输出。注意,在 C 语言中,我们需要手动管理内存,因此需要在程序结束前释放动态分配的内存。
阅读全文