evaluate a polyome for a given value

Viewed 37

I wanted to evaluate a polynome for a given value so I have used a linked list to store the coefficients and the exponants,and I have defined a function evaluate() to evaluate the polynome for a given value, but I do have a problem when it comes to the output it always shows the value 0.00000

can I get some help ? thanks in advance.

here's the full code :

#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
    int coef;
    int expo;
    struct list* next;
}list;
int compare(char* s1,char* s2)
{
    int i=0;
    char c1,c2;
    do
    {
        c1= (*(s1+i));
        c2= (*(s2+i));
        i++;
        if(c2 == '\0' || c1 == '\0')
            return c1-c2;
    }while(c1==c2);
    return c1-c2;
}
int transform(char* arr)
{
    int i,sign=0;
    int s=0;
    if((*arr) == '-')  sign=1;
    for(i=0;arr[i]!='\0';i++)
    {
        if(arr[i]>=0 && arr[i]<=9)
            s=s*10+(arr[i]-'0');
    }
    if(sign)    return -s;
    return s;
}
list* insert(list* head,char* coef,int expo)
{
    list* node=(list*)malloc(sizeof(list));
    if(node==NULL)
    {
        printf("Stack Overflow");
        exit(1);
    }
    node->next=NULL;
    node->coef=transform(coef);
    node->expo=expo;
    if(head==NULL)  return node;
    list* temp=head;
    while(temp && temp->next)
        temp=temp->next;
    temp->next=node;
    return head;
}
float power_of(float x,int expo)
{
    if(expo==0) return 1;
    int i=1;
    float s=1;
    if(expo > 0)
        while(i++ <= expo)
            s*=x;
    else if (expo < 0)
        while(i++ <= -expo)
            s*=1.0/x;
    return s;
}
float evaluate(list* head,float x)
{
    if(head==NULL)  return 0;
    float s=0.0;
    while(head)
    {
        s+=(head->coef)*power_of(x,head->expo);
        head=head->next;
    }
    return s;
}
int main()
{
    list* head=NULL;
    char coef[11];
    int expo,i=1;
    float x;

    printf("insert the polynome <type end to stop>:\n");
    do
    {
        printf("insert the coefficient %d> : ",i);
        scanf("%s",coef);
        if(compare(coef,"end"))
        {
            printf("insert the exposnant %d> : ",i++);
            scanf("%d",&expo);
            head=insert(head,coef,expo);
        }
    }while(compare(coef,"end"));
    printf("insert a value to evaluate the polynome : ");
    scanf("%f",&x);
    float value=evaluate(head,x);
    printf("output : %f ",value);
    return 0;
}
0 Answers
Related