1.简单题直接开辟数组在对应的下标作为指数的情况下,保存每一项的系数即可。注意数组开的足够大,至少是2000;
2.我用的链表,有一处坑点是注意系数可能取负值。
#include<iostream>
#include<iomanip>
using namespace std;
typedef struct node{
int e;
float c;
node *next;
}*Node;//结构体存储每一项的指数e和系数c
int main()
{
cout.setf(ios::showpoint); //将小数精度后面的0显示出来
int a;
node *str1, *str2,*result;
cin >> a;
Node p;
str1 = (Node)malloc(sizeof(Node));
p = str1;
while (a--)
{
Node q = (Node)malloc(sizeof(node));
p->next = q;
p = p->next;
cin >> p->e>>p->c;
}
p->next = NULL;
cin >> a;
str2 = (Node)malloc(sizeof(Node));
p = str2;
while (a--)
{
Node q = (Node)malloc(sizeof(Node));
p->next = q;
p = p->next;
cin >> p->e >> p->c;
}
p->next = NULL;//输入分别将两个多项式写入链表str1和str2
int sum = 0;
result = (Node)malloc(sizeof(node));
p = result;
p->next = NULL;
p = str1;
while (p->next)
{
p = p->next;
Node q = str2;
while (q->next)
{
q = q->next;
int e = p->e + q->e;
float c = p->c*q->c;
for (Node r = result; r!= NULL; r = r->next)
{
if (r->next==NULL||e > r->next->e)//如果result中没有指数为e的一项,则开辟新的结点
{
Node t = (Node)malloc(sizeof(node));
sum++;
t->e = e;
t->c = c;
t->next = r->next;
r->next = t;
break;
}
else if (e == r->next->e)
{
r->next->c += c;
if (r->next->c == 0.0)//如果某一项系数为0,则删去该结点
{
r->next = r->next->next;
sum--;
}
break;
}
}
}
}
p = result;
cout << sum;
if (sum==0)
cout << endl;
while (sum--)
{
p = p->next;
cout << ' ' << p->e<< ' ';
printf("%.1f", p->c);
if (p->next==NULL)
{
cout << endl;
break;
}
}
system("pause");
return 0;
}