随机输入两个一元多项式,实现两个多项式相加,输出相加后的一元多项式。要求用标准的C语言实现,提交可执行代码。
时间: 2024-10-07 22:04:49 浏览: 68
在C语言中,我们可以使用数组来存储多项式的系数,并通过循环遍历实现多项式的相加。下面是一个简单的示例,假设我们只考虑一次项、二次项等简单的一元多项式:
```c
#include <stdio.h>
typedef struct {
int degree; // 次数
double coefficients[10]; // 系数数组,这里足够处理大多数一次和二次多项式
} Polynomial;
// 添加两个多项式
void addPolynomials(Polynomial *poly1, Polynomial *poly2, Polynomial *result) {
result->degree = poly1->degree > poly2->degree ? poly1->degree : poly2->degree;
for (int i = 0; i <= result->degree; i++) {
if (i == 0)
result->coefficients[i] = poly1->coefficients[0] + poly2->coefficients[0];
else
result->coefficients[i] = poly1->coefficients[i] + poly2->coefficients[i];
}
}
// 打印多项式
void printPolynomial(const Polynomial *poly) {
printf("Degree: %d\n", poly->degree);
printf("Coefficients: ");
for (int i = 0; i <= poly->degree; i++)
printf("%.2lf ", poly->coefficients[i]);
printf("\n");
}
int main() {
Polynomial p1, p2, sum;
// 输入第一个多项式系数
printf("Enter the coefficients of polynomial 1 (separated by spaces): ");
int deg1;
scanf("%d", °1);
for (int i = 0; i <= deg1; i++) {
scanf("%lf", &p1.coefficients[i]);
}
p1.degree = deg1;
// 输入第二个多项式系数
printf("Enter the coefficients of polynomial 2 (separated by spaces): ");
int deg2;
scanf("%d", °2);
for (int i = 0; i <= deg2; i++) {
scanf("%lf", &p2.coefficients[i]);
}
p2.degree = deg2;
// 相加并打印结果
addPolynomials(&p1, &p2, &sum);
printPolynomial(&sum);
return 0;
}
```
阅读全文