mercredi 25 février 2015

Can't decode a polynomial properly


#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;
}




In my code I am asking user to input a polynomial in the form like: -5x^2+7y^3-19z+5



Everything seems fine but two problems in decoding this polynomial and storing in the linked list form:



First bug comes when the first-most coefficient is positive in polynomial like 17x^3-13z+5

In this case a very long integer value (most probably garbage value) gets store in the respected node of linked list.



Second bug is when there is no first coefficient like x^7-18y^3+z-13

In this case 0 gets stored in the respected node of linked list. In other terms of polynomial, like z in example above, where there is no coefficient 1 gets stored in the coeffient part of the node.



So problem arises with the first coefficient only that too a 'positive coeff' or 'no coefficient' at all.


Aucun commentaire:

Enregistrer un commentaire