用数据与结构写多项式相乘
时间: 2024-02-17 12:00:33 浏览: 20
好的,以下是一个示例的 C 语言代码,用于实现多项式相乘:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_DEGREE 10
typedef struct {
int degree;
int coeff[MAX_DEGREE + 1];
} Polynomial;
void init_poly(Polynomial *poly) {
int i;
for (i = 0; i <= MAX_DEGREE; i++) {
poly->coeff[i] = 0;
}
poly->degree = 0;
}
void read_poly(Polynomial *poly) {
printf("Enter the degree of the polynomial: ");
scanf("%d", &poly->degree);
printf("Enter the coefficients of the polynomial from highest to lowest degree: ");
int i;
for (i = poly->degree; i >= 0; i--) {
scanf("%d", &poly->coeff[i]);
}
}
void display_poly(Polynomial poly) {
int i;
printf("%d", poly.coeff[poly.degree]);
for (i = poly.degree - 1; i >= 0; i--) {
if (poly.coeff[i] != 0) {
printf(" + %d*x^%d", poly.coeff[i], i);
}
}
printf("\n");
}
Polynomial multiply_poly(Polynomial poly1, Polynomial poly2) {
Polynomial result;
init_poly(&result);
if (poly1.degree + poly2.degree > MAX_DEGREE) {
printf("Error: Degree of resulting polynomial exceeds max degree\n");
exit(EXIT_FAILURE);
}
int i, j;
for (i = 0; i <= poly1.degree; i++) {
for (j = 0; j <= poly2.degree; j++) {
result.coeff[i+j] += poly1.coeff[i] * poly2.coeff[j];
}
}
result.degree = poly1.degree + poly2.degree;
return result;
}
int main() {
Polynomial poly1, poly2, result;
init_poly(&poly1);
init_poly(&poly2);
init_poly(&result);
printf("Enter the first polynomial:\n");
read_poly(&poly1);
printf("Enter the second polynomial:\n");
read_poly(&poly2);
result = multiply_poly(poly1, poly2);
printf("\nResult:\n");
display_poly(result);
return 0;
}
```
这个示例程序定义了一个“多项式”结构体,并实现了一些常用的多项式操作函数,例如“初始化多项式”、“读取多项式”、“显示多项式”和“相乘多项式”。程序创建了两个多项式,并使用相乘多项式函数将它们相乘,然后打印结果。