两个多项式相乘

#include<stdio.h>
#include<stdlib.h>
#define swap(x, y, t) ((t)=(x),(x)=(y),(y)=(t))
#define MAX_SIZE 1000

void readpoly( int *starta, int *startb, int *finisha, int *finishb);
void muti(int starta, int startb, int finisha, int finishb, int *startd, int *finishd);
void printpoly(int s, int e);

typedef struct info{
	float coef;
	int expon;
}polynomial;
int flag;
polynomial data[MAX_SIZE], temp[MAX_SIZE + 1], re[MAX_SIZE];
int main(void)
{
	int starta, finisha, startb, finishb, startd, finishd;
	readpoly(&starta, &startb, &finisha, &finishb);
	muti(starta, startb, finisha, finishb, &startd, &finishd);
	printpoly(startd, finishd);
	return 0;
}

void readpoly( int *starta, int *startb, int *finisha, int *finishb)
{
	int i = 0;
	printf("2*x^3 + 3*x^2 + x + 7: 2 3 3 2 1 1 7 0(-1 -1 to end input)\n");
	printf("Please enter the first polynomial: ");
	while(scanf("%f%d", &data[i].coef, &data[i].expon) != EOF && data[i].coef != -1 && data[i].expon != -1)
		i++;
	*starta = 0;
	*finisha = --i;
	printf("Please enter the second polynomial: ");
	i++;
	*startb = i;
	while(scanf("%f%d", &data[i].coef, &data[i].expon) != EOF && data[i].coef != -1 && data[i].expon != -1)
		i++;
	*finishb = --i;
}
void muti(int starta, int startb, int finisha, int finishb, int *startd, int *finishd)
{
	int i, j, k = 0, p = 0;
	for(i = starta; i <= finisha; i++)
		for(j = startb; j <= finishb; j++){
			temp[k].coef = data[i].coef * data[j].coef;
			temp[k++].expon = data[i].expon + data[j].expon;
		}
	for(i = 0; i < k - 2; i++)
		for(j = 1; j < k - i; j++)
			if(temp[j].expon > temp[j - 1].expon)
				swap(temp[j], temp[j - 1], temp[MAX_SIZE]);
	for(i = 0; i <= k - 1;){
		j = i;
		while(temp[++i].expon == temp[j].expon)
			temp[j].coef += temp[i].coef;
		re[p].coef = temp[j].coef;
		re[p++].expon = temp[j].expon;
	}
	*startd = 0;
	*finishd = --p;
}
void printpoly(int s, int e)
{
	int i;
	for(i = s; i < e; i++)
		printf("%.1fx^%d + ", re[i].coef, re[i].expon);
	printf("%.1fx^%d\n", re[e].coef, re[e].expon);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值