多项式相乘(C语言)

#include<stdio.h>
#include<stdlib.h>
typedef struct node* list;
struct node
{
	double coef;
	int expon;
	list next;
};
list create()                                                    //创建 
{
	int n;
	printf("输入多项式的项数:");
	scanf("%d", &n);
	printf("输入多项式的系数和指数(空格为界):");
	list head = (list)malloc(sizeof(struct node)), now = head, last;
	for (; n--; now = last)
	{
		last = (list)malloc(sizeof(struct node));
		scanf("%lf%d", &last->coef, &last->expon);
		now->next = last;
	}
	now->next = NULL;
	return head;
}
list mul(list a, list b)                                         //相乘 
{
	list head = (list)malloc(sizeof(struct node)), now = head, last;
	for (list i = a->next; i != NULL; i = i->next)for (list j = b->next; j != NULL; j = j->next)
	{
		last = (list)malloc(sizeof(struct node));
		last->coef = i->coef * j->coef;                         // 系数
		last->expon = i->expon + j->expon;                      // 指数
		now->next = last;
		now = last;
	}
	now->next = NULL;
	return head;
}
void sort(list a)                                              //排序并且将expon相同的合并 
{
	if (a->next == NULL || a->next->next == NULL)return;
	list r = a, i;
	while (r->next->next != NULL)r = r->next;
	for (; 1; r = i)
	{
		if (r != a)
			for (i = a; 1; i = i->next)
			{
				list j = i->next, k = j->next;
				if (j->expon < k->expon)
				{
					if (j == r)r = k;
					else if (k == r)r = j;
					i->next = k, j->next = k->next, k->next = j;
				}
				if (i->next == r)break;
			}
		if (r->next->next != NULL)
		{
			list j = r->next, k = j->next;
			if (j->expon == k->expon)j->coef += k->coef, j->next = k->next;
		}
		if (r == a)break;
	}
}
void show(list a)                                               //输出 
{
	list i = a->next;
	if (i != NULL)
	{
		printf("%g*x^%d", i->coef, i->expon);
		for (i = i->next; i != NULL; i = i->next)if (i->coef)
		{
			if (i->coef > 0)putchar('+');
			printf("%g*x^%d", i->coef, i->expon);
		}
	}
	putchar('\n');
	return;
}
int main()
{
	list a = create(), b = create(), c = mul(a, b);
	show(a);
	show(b);
	sort(c);
	show(c);
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值