#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Polynomial
{
float coef;
int expn;
struct Polynomial *next;
}*Polyn;
int m; // 项数
void InitPolyn(Polyn *P);
void CreatPolyn(Polyn *P,int m);//创建一个多项式
void ShowPolyn(Polyn P);//打印出多项式
void SortPolyn(Polyn P);//按序排列
void AddPolyn(Polyn Pa,Polyn Pb,Polyn Pc);//Pc = Pa + Pb
void SubPolyn(Polyn Pa,Polyn Pb,Polyn Pc);//Pc = Pa - Pb
void valPolyn(Polyn *P,int x);//求多项式当X为多少的值
void InitPolyn(Polyn *P)
{
*P = (Polyn )malloc(sizeof(Polyn));
(*P)->coef = 0.0;
(*P)->expn = 0;
(*P)->next = NULL; //初始化,加上头结点,便于操作
}
void CreatPolyn( Polyn *P ) // 去掉指针符号
{
float c;
int e,i;
Polyn s,q;
q = *P; // 去掉指针符号
printf("请输入项数: ");
scanf("%d",&m);
for(i=1;i<=m;i++)
{
printf("请输入第%d项的系数和指数: ",i);
scanf("%f%d",&c,&e);
s = (Polyn )malloc(sizeof(Polyn));
s->coef = c;
s->expn = e;
s->next = NULL;
q->next = s;
q = s;
q->next = NULL;
}
}
/*
void SortPolyn(Polyn P) // 什么排序法?
{
Polyn temp;
while(P!=NULL)
{
if( P->expn < P->next->expn )
{
temp = P->next;
P->next = P;
P = temp;
}
// 感觉少了这一句 P = P ->next;
}
}
*/
void SortPolyn( Polyn *P )
{
Polyn q, g;
int i, j, c, e;
// 冒泡排序法
g = (*P);
for( i = 1; i < m; i++ )
{
q = g ->next;
for( j = 0; j < m - i; j++ )
{
// 用 temp 来处理好像 行不通
if( ( q ->next ) && ( q->expn < q->next->expn ) )
{
c = q ->coef;
e = q ->expn;
q ->coef = q ->next ->coef;
q ->expn = q ->next ->expn;
q ->next ->coef = c;
q ->next ->expn = e;
}
q = q ->next;
}
g = g ->next;
}
}
void ShowPolyn(Polyn P)
{
Polyn pchar;
pchar = P->next;
while(pchar)
{
printf("%.3f X^%d\t",pchar->coef,pchar->expn);
pchar = pchar->next;
}
printf("\n");
}
int main( void )
{
Polyn Pa;
InitPolyn(&Pa);
CreatPolyn(&Pa);
ShowPolyn(Pa);
system("pause");
SortPolyn(&Pa);
ShowPolyn(Pa);
return 0; // 最好加上
}
f:\结果.jpg |