栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

多项式相乘(C语言)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

多项式相乘(C语言)

#include
#include
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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/303940.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号