一元多项式加法运算(一)

采用结构体

#include<iostream>
using namespace std;
struct data
{
	int x;
	int y;
}stu11[100]={0,0},stu22[100]={0,0};//结构体 ,x为系数,y为指数 

int main()
{
	void change(struct data a[],int n);
	int i=-1,j=-1;
    char c=',';
    int flag1;
	int flag2;
	do
	{
		i++;
		cin>>stu11[i].x>>c>>stu11[i].y;
		if(stu11[i].x==0&&stu11[i].y==0)
    {
    	flag1=0;
	}
	else flag1=1;
	}while(flag1==1);
	//输入第一个式子的输入 
	do
	{
		j++;
		cin>>stu22[j].x>>c>>stu22[j].y;
		if(stu22[j].x==0&&stu22[j].y==0)
	{
		flag2=0;
	}
	else
	flag2=1;
	}while(flag2==1);
	//第二个式子的输入 
	int p,q;
	for(p=0;p<i;p++)
	{
		for(q=0;q<j;q++)
		{
			if(stu11[p].y==stu22[q].y)
			{
				stu11[p].x+=stu22[q].x;
			}
		}
	}//把第二个式子中与第一个式子指数相同的前面系数先加到第一个式子中 (以下都是以第一个式子为基础) 
	int m=i;
	int count=0;
	for(p=0;p<j;p++)
	{
		for(q=0;q<i;q++)
		{
			if(stu22[p].y!=stu11[q].y)
			{
				count++;
			}
		}
		if(count==i)
		{
			
			stu11[m++]=stu22[p];
		}
		count=0;
	}//把第二个式子中与第一个式子中指数完全不同的指数项接在第一个式子的后面 
    change(stu11,m);//进行第一个式子的从小到大排序 
    for(p=0;p<m-1;p++)
    {
    	if(stu11[p].x!=0)
    	{
    		cout<<stu11[p].x<<"x^"<<stu11[p].y<<"+";
		}
	}
	cout<<stu11[m-1].x<<"x^"<<stu11[m-1].y;//输出非零指数的项 
	return 0;
}

//函数进行排序 
void change(struct data a[],int n)
{
	struct data temp;
	int i,j;
	for(i=0;i<n;i++)
	{
		for(j=i+1;j<n;j++)
		{
			if(a[i].y>a[j].y)
			{
				temp=a[i];
				a[i]=a[j];
				a[j]=temp;
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值