#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);
}
两个多项式相乘
最新推荐文章于 2022-10-18 20:20:48 发布