#include<stdio.h>
#include<iostream.h>
using namespace std;
#define MAX 100
typedef struct{
int coefarray[MAX+1];
int highpower;//最高项指数
} polyarray;
//创建多项式
void Create(polyarray *L)
{
int i,n,coef,index;
L->highpower=0;
for(i=0;i<MAX+1;i++)
{
L->coefarray[i]=0;
}
cout<<"输出多项式的项数:";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"请输入第"<<i<<"项的系数和指数:";
cin>>coef>>index;
if(L->highpower<index);
L->highpower=index;
L->coefarray[index]=coef;
}
}
//输出多项式
void Show(polyarray *L)
{
if(L->coefarray[0]!=0)
cout<<L->coefarray[0];
for(int i=1;i<=L->highpower;i++)
{
if(L->coefarray[i]>0)
cout<<"+"<<L->coefarray[i]<<"x^"<<i;
else if(L->coefarray[i]<0)
cout<<L->coefarray[i]<<"x^"<<i;
}}
//初始化
void Init(polyarray *L)
{
int i;
for(i=0;i<=MAX+1;i++)
{
L->coefarray[i]=0;
}
L->highpower=0;
}
//多项式相加
void Add(polyarray *L1,polyarray *L2,polyarray *L3)
{
int i;
if(L1->highpower>L2->highpower)
L3->highpower=L1->highpower;
else
L3->highpower=L2->highpower;
for(i=0;i<=L3->highpower;i++)
{
L3->coefarray[i]=L1->coefarray[i]+L2->coefarray[i];
}}
//多项式相减
void Sub(polyarray *L1,polyarray *L2,polyarray *L3)
{
int i;
if(L1->highpower>L2->highpower)
L3->highpower=L1->highpower;
else
L3->highpower=L2->highpower;
for(i=0;i<=L3->highpower;i++)
{
L3->coefarray[i]=L1->coefarray[i]-L2->coefarray[i];
}}
//多项式相乘
void Mult(polyarray *L1,polyarray *L2,polyarray *L3)
{
L3->highpower=L1->highpower+L2->highpower;
for(int i=0;i<=L1->highpower;i++)
{
for(int j=0;j<=L2->highpower;j++)
{
L3->coefarray[i+j]+=L1->coefarray[i]*L2->coefarray[j];
}} }
//菜单
void Menu()
{
cout<<"\t***************************************\n";
cout<<"\t>>>>>>> 1. 创建多项式 <<<<<<<\n";
cout<<"\t>>>>>>> 2. 多项式加法 <<<<<<<\n";
cout<<"\t>>>>>>> 3. 多项式减法 <<<<<<<\n";
cout<<"\t>>>>>>> 4. 多项式乘法 <<<<<<<\n";
cout<<"\t>>>>>>> 0. 退出系统 <<<<<<<\n";
cout<<"\t***************************************\n";
}
int main()
{
polyarray *L1,*L2,*L3;
L1=(polyarray*)malloc(sizeof(polyarray));
L2=(polyarray*)malloc(sizeof(polyarray));
L3=(polyarray*)malloc(sizeof(polyarray));
int num;
Menu();
while(1)
{
cout<<"请输入要操作的序号:";
cin>>num;
switch(num)
{
case 1:
Create(L1);
cout<<"第一个多项式为:";
Show(L1);
cout<<endl<<endl;
Create(L2);
cout<<"第二个多项式为:";
Show(L2);
cout<<endl<<endl;
break;
case 2:
Init(L3);
Add(L1,L2,L3);
cout<<"相加后的结果为:";
Show(L3);
cout<<endl<<endl;
break;
case 3:
Init(L3);
Sub(L1,L2,L3);
cout<<"相减后的结果为:";
Show(L3);
cout<<endl<<endl;
break;
case 4:
Init(L3);
Mult(L1,L2,L3);
cout<<"相乘后的结果为:";
Show(L3);
cout<<endl<<endl;
break;
case 0:
exit(1);
break;
}
}
return 0;}
用五个函数分别实现一元多项式的创建、输出、加法、减法和乘法;然后在主函数中调用这些函数实现这些功能的展示(以菜单的形式呈现)。