用c语言设计一个一元稀疏多项式简单乘法计算器
时间: 2023-05-19 14:02:05 浏览: 90
以下是一个简单的一元稀疏多项式简单乘法计算器的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_TERMS 100
typedef struct {
int coef;
int exp;
} Term;
void read_poly(Term poly[]);
void print_poly(Term poly[]);
void add_term(Term poly[], int *n, int c, int e);
void mult_poly(Term poly1[], Term poly2[], Term poly3[]);
int main() {
Term poly1[MAX_TERMS], poly2[MAX_TERMS], poly3[MAX_TERMS];
int n1 = 0, n2 = 0, n3 = 0;
printf("Enter the first polynomial:\n");
read_poly(poly1);
printf("Enter the second polynomial:\n");
read_poly(poly2);
mult_poly(poly1, poly2, poly3);
printf("The product of the two polynomials is:\n");
print_poly(poly3);
return 0;
}
void read_poly(Term poly[]) {
int c, e;
do {
printf("Enter a term (coef, exp): ");
scanf("%d %d", &c, &e);
if (c != 0) {
add_term(poly, &n1, c, e);
}
} while (c != 0);
}
void print_poly(Term poly[]) {
int i;
for (i = 0; i < n3; i++) {
printf("%d*x^%d ", poly[i].coef, poly[i].exp);
if (i < n3 - 1) {
printf("+ ");
}
}
printf("\n");
}
void add_term(Term poly[], int *n, int c, int e) {
if (*n >= MAX_TERMS) {
fprintf(stderr, "Too many terms in the polynomial\n");
exit(1);
}
poly[*n].coef = c;
poly[*n].exp = e;
(*n)++;
}
void mult_poly(Term poly1[], Term poly2[], Term poly3[]) {
int i, j, k;
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
int c = poly1[i].coef * poly2[j].coef;
int e = poly1[i].exp + poly2[j].exp;
add_term(poly3, &n3, c, e);
}
}
}
```
这个程序会要求用户输入两个多项式,然后计算它们的乘积,并输出结果。
阅读全文