一、题目:
二、代码:[用数组实现]
#include<stdio.h>
const int maxx = 1e3;
struct Node{
int x;
int m;
int isok;//代表已经相加?
};
Node a[maxx];
Node b[maxx];
int cnt1,cnt2;
/*
3
2 3
1 2
2 4
3
3 5
2 3
5 4
*/
void add(Node a[],Node b[],int cnt1,int cnt2) {
int index = 0;
for(int i=0;i<cnt1;i++) {
for(int j=0;j<cnt2;j++) {
if(a[i].m == b[j].m) {
b[j].isok = 1;
a[i].x = a[i].x + b[j].x;
break;
}
}
}
//输出
printf("\n相加后的结果:");
for(int i=0;i<cnt1;i++) {
printf("%d*x^%d",a[i].x,a[i].m);
if(cnt2 != 0) printf(" + ");
}
for(int j=0;j<cnt2;j++) {
if(b[j].isok == 0) {
printf("%d*x^%d + ",b[j].x,b[j].m);
}
}
}
void subtract(Node a[],Node b[],int cnt1,int cnt2) {
//赋值,将第二个多项式的系数赋为其相反数
for(int j=0;j<cnt2;j++) {
b[j].x = -b[j].x;
}
//下面方法跟add一样,因为:类比为两数相减,等同于第一个数+(-1)*第二个数.
int index = 0;
for(int i=0;i<cnt1;i++) {
for(int j=0;j<cnt2;j++) {
if(a[i].m == b[j].m) {
b[j].isok = 1;
a[i].x = a[i].x + b[j].x;
break;
}
}
}
//输出
printf("\n相减后的结果:");
for(int i=0;i<cnt1;i++) {
if(a[i].x < 0) printf(" ");
printf("%d*x^%d",a[i].x,a[i].m);
if(a[i+1].x > 0) printf(" + ");
}
for(int j=0;j<cnt2;j++) {
if(b[j].isok == 0) {
if(b[j].x < 0) printf(" ");
printf("%d*x^%d",b[j].x,b[j].m)