两个多项式相加

本文探讨了智能算法在不同技术领域的应用,包括前端开发、后端开发、移动开发等,展示了算法如何促进技术创新与优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 1000

void readpoly( int *starta, int *startb, int *finisha, int *finishb);
int cmp(int a, int b);
void attach(float coefficient, int expoent);
void padd(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 avail;
polynomial data[MAX_SIZE];
int main(void)
{
	int starta, finisha, startb, finishb, startd, finishd;
	readpoly(&starta, &startb, &finisha, &finishb);
	padd(starta, startb, finisha, finishb, &startd, &finishd);
	printpoly(startd, finishd);
	return 1;
}
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;
	avail = ++i;
}
void padd(int starta, int startb, int finisha, int finishb, int *startd, int *finishd)
{
	float coefficient;
	*startd = avail;
	while(starta <= finisha && startb <= finishb)
		switch(cmp(data[starta].expon, data[startb].expon))
		{			/*a < b*/
			case -1:
				attach(data[startb].coef, data[startb].expon);
				startb++;
				break;
			case 0:															/*a == b*/
				coefficient = data[starta].coef + data[startb].coef;
				if(coefficient)
					attach(coefficient, data[starta].expon);
					starta++;
					startb++;
					break;
			case 1:															/*a > b*/
				attach(data[starta].coef, data[starta].expon);
				starta++;
		}
		for(; starta <= finisha; starta++)
			attach(data[starta].coef, data[starta].expon);
		for(; startb <= finishb; startb++)
			attach(data[startb].coef, data[startb].expon);
		*finishd = avail - 1;
}
void attach(float coefficient, int expoent)
{
	if(avail >= MAX_SIZE){
		printf("Overloaded\n");
		exit(1);
	}
	data[avail].coef = coefficient;
	data[avail++].expon = expoent;
}
int cmp(int a, int b)
{
	if(a < b)
		return -1;
	if(a == b)
		return 0;
	return 1;
}
void printpoly(int s, int e)
{
	int i;
	for(i = s; i < e; i++)
		printf("%.1fx^%d + ", data[i].coef, data[i].expon);
	printf("%.1fx^%d\n", data[e].coef, data[e].expon);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值