一元多项式计算
我想用C写个一元多项式计算程序,以下是我的代码#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>
#include <memory.h>
#include <assert.h>
typedef struct Node
{
ElemType Coefficient;// 多项式的系数
ElemType Index;//多项式的指数
struct Node *next; // 链表中结点元素的指针
} LNode, *LinkList;
void print_choice()
{
printf("功能菜单\n");
printf("=========================\n");
printf("[1] 多项式加法\n");
printf("[2] 多项式减法\n");
printf("[3] 多项式乘法\n");
printf("[4] 多项式除法\n");
printf("[5] 多项式求导\n");
printf("[6] 多项式求值\n");
printf("[0] 退出\n");
printf("=========================\n");
}
bool InitList(LinkList *L)
{
*L = (LinkList)malloc(sizeof(LNode));
if(!*L)
{
printf("creat error!");
}
(*L) ->next = NULL;
return true;
}
bool ListInsert(LinkList L, int i, ElemType e1,ElemType e2)
{
int j = 0;
LinkList p=L,s;
while(p&&j<i-1)
{
p = p ->next;
j++;
}
if(!p||j > i-1)
{
return false;
}
s = (LinkList)malloc(sizeof(LNode));
s ->Coefficient = e1;
s ->Index = e2;
s ->next = p ->next;
p ->next = s;
return true;
}
void Plus(LinkList l1,LinkList l2)
{
int Coefficient_1,Coefficient_2,Index_1,Index_2;
int i,j=0,sum;
LinkList p1;
LinkList p2;
LinkList r;
LinkList temp;
p1 = l1->next;
p2 = l2->next;
r = l1;
printf("\n请输入您要输入第一个的多项式的项数:");
scanf("%d",&i);
printf("\n请输入第一个多项式的系数和指数:\n");
while(j<i)
{
scanf("%d",&Coefficient_1);
scanf("%d",&Index_1);
if(Coefficient_1!=0)
{
ListInsert(l1,j+1,Coefficient_1,Index_1);
}
j++;
}
printf("\n请输入您要输入第二个的多项式的项数:");
scanf("%d",&i);
printf("\n请输入第二个多项式的系数和指数:\n");
j = 0;
while(j<i)
{
scanf("%d",&Coefficient_2);
scanf("%d",&Index_2);
if(Coefficient_2!=0)
{
ListInsert(l2,j+1,Coefficient_2,Index_2);
}
j++;
}
while(p1&&p2)
{
if(p1->Index>p2->Index)
{
r ->next = p2;
r = r->next;
p2 = p2 ->next;
}
else if(p1->Index<p2->Index)
{
r ->next = p1;
r = r->next;
p1 = p1->next;
}
else if(p1->Index==p2->Index)
{
sum = p1 ->Coefficient + p2 ->Coefficient;
if(sum!=0)
{
p1->Coefficient = sum;
r ->next = p1;
p1 = p1->next;
temp = p2;
p2 = p2 ->next;
free(temp);
}
else
{
temp = p1 ->next;
free(p1);
p1 = temp;
temp = p2 ->next;
free(p2);
p2 = temp;
}
}
}//while
if(p1!=NULL)
{
r ->next = p1;
}
else if(p2!=NULL)
{
r->next = p2;
}
}
void print(LinkList l1)
{
LinkList p1;
p1 = l1 ->next;
printf("计算结果如下:\n");
while(p1->next!=NULL)
{
printf("%dx^%d + ",p1->Coefficient,p1->Index);
p1 = p1 ->next;
}
system("PAUSE");
}
int main()
{
int choice;
LinkList l1;
LinkList l2;
InitList(&l1);
InitList(&l2);
printf("一元多项式计算器\n\n");
print_choice();
while(1)
{
printf("\n请输入你的选择:(0~6)");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
Plus(l1,l2);
print(l1);
}
case 2:
{
//Minus();
}
case 3:
{
//Multiply();
}
case 4:
{
//Division();
}
case 5:
{
//Derivation();
}
case 6:
{
//Evaluation();
}
case 0:
{
exit(0);
}
}
}
system("PAUSE");
return 0;
}
请高手帮忙检查哪错了,谢谢!(不胜感激)~
[ 本帖最后由 guxiao1228 于 2009-10-17 09:54 编辑 ]