#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct polynomial{
int coeff;
char var;
int exp;
struct polynomial *link;
} poly;
poly* decode(char*);
main()
{
char polynomial[100];
poly *first, *second;
printf("\n---Enter 1st polynomial---\n\n");
scanf("%s",polynomial);
first=decode(polynomial);
printf("\n---Enter 2nd polynomial---\n\n");
scanf("%s",polynomial);
second=decode(polynomial);
//More statements further
return 0;
}
/*--- Decoding Polynomial ---*/
poly* decode(char *polynomial)
{
poly *p=NULL, *q=NULL, *temp=NULL;
int i=0, sign;
short coeff_entry=TRUE, exp_entry=FALSE, var_visited=FALSE, exp_visited=FALSE, coeff_visited=FALSE;
while(polynomial[i]!='\0')
{
temp=(poly*)malloc(sizeof(poly));
if(!temp)
{
printf("Error! Memory not allocated\n");
exit(1);
}
if(polynomial[i]==43) {i++; sign=1;}
if(polynomial[i]==45) {i++; sign=-1;}
while(1)
{
if((polynomial[i]>=48&&polynomial[i]<=57)&&coeff_entry==TRUE)
{
temp->coeff=10*(temp->coeff)+(polynomial[i]-48);
coeff_visited=TRUE;
}
else if((polynomial[i]>=65&&polynomial[i]<=90)||(polynomial[i]>=97&&polynomial[i]<=122))
{
temp->var=polynomial[i];
coeff_entry=FALSE;
exp_entry=TRUE;
var_visited=TRUE;
}
else if((polynomial[i]>=48&&polynomial[i]<=57)&&exp_entry==TRUE)
{
temp->exp=10*(temp->exp)+(polynomial[i]-48);
exp_visited=TRUE;
}
else if(polynomial[i]==43||polynomial[i]==45||polynomial[i]=='\0')
{
exp_entry=FALSE;
coeff_entry=TRUE;
if(var_visited&&!exp_visited)
{
temp->exp=1;
!var_visited;
!exp_visited;
}
if(!coeff_visited)
{
!coeff_visited;
temp->coeff=1;
}
temp->coeff*=sign;
break;
}
i++;
}
//These lines are for debugging purpose only
printf("\nCoefficient of the term is: %d\n",temp->coeff);
printf("Variable of the term is: %c\n",temp->var);
printf("Exponent of the term is: %d\n",temp->exp);
temp->link=NULL;
if(p==NULL) p=q=temp;
else
{
q->link=temp;
q=q->link;
}
}
return p;
}
在我的代码中,我要求用户输入如下形式的多项式: -5x ^ 2 + 7y ^ 3-19z + 5
一切似乎都很好但解码这个多项式并以链表形式存储有两个问题:
第一个错误来自多项式中第一大系数为正,如 17 x ^ 3-13z + 5
在这种情况下,一个非常长的整数值(最可能是垃圾值)存储在链表的受尊重节点中。
第二个错误是没有第一个系数,如 x ^ 7-18y ^ 3 + z-13
在这种情况下, 0 存储在链表的受尊重节点中。在多项式的其他项中,如上例中的 z ,其中没有系数 1 存储在节点的系数部分中。
所以问题出现在第一个系数上,只有太多的“正系数”才会出现问题。或者没有系数&#39;一点都不。
答案 0 :(得分:0)
您的代码中存在许多错误,最重要的是像
这样的表达式!value;
你需要分配它,喜欢
value = !value;
如果在下一个令牌前面没有sign
符号时您没有初始化'+'
,则需要将其初始化为1
,检查是否有{{1}然后将其设置为'-'
,否则忽略-1
。
现在我添加了固定代码,试一试
'+'