Home > Software engineering >  Determination of polynomials
Determination of polynomials

Time:12-28

I need help solving this task, if anyone had a similar problem it would help me a lot.

The task is: Write a program that calculates the degree and polynomial p(x) for a given x.

For example:

Enter n:2 //degree of polynomial and function degree
Enter x:2
x^n=4
Enter coefficients of polynomial:
a[0]=1
a[1]=2
a[2]=3
P(x)=3*x^2   2*x^1  1*x^0 = 17

I did it like this:

 #include <stdio.h>
 #include <stdlib.h>
 #include <math.h>
 #define MAX 100
 /*
 */
 typedef struct polynomial {
     double coef[MAX];
 } POLYNOMIAL;
 double degree(double ,int );
 double px(POLYNOMIAL ,double );

int main()
{
    POLYNOMIAL p;
    double x,pom;
    int n;
    printf("Enter degree (n>=0):");
    scanf("%d",&n);
    while(n<1 || n>MAX)
    {
        printf("Enter degree (n>=0):");
        scanf("%d",&n);
    }
    printf("Enter x:");
    scanf("%lf",&x);
    pom=degree(x,n);
    printf("%.2lf^%d =%lf",x,n,pom);
    printf("\nEnter coefficients of polynomial :\n");
    for(int i=0;i<=n;i  )
    {
        printf("a[%d]:",i);
        scanf("%lf",&p.coef[i]);
    }
    return 0;
}

double degree(double x,int n)
{
    double degree=1;
    if(n==0)
    {
        return 1;
    }
    for(int i=1;i<=n;i  )
    {
        degree*=x;
    }
    return degree;
}

double px(POLYNOMIAL p,double x)
{
    double sum=0;
    for(int j=0;j<"I don't know what to put here";j  )
    {
        sum =(double)p.coef[j]*degree(x,j);
    }
    printf("%lf",sum);
}

The problem arises when calculating polynomials, because I don't know what to put as a condition in the for loop, there should be j < of the length of the array entered, that is, of degree n, but n cannot be used as a parameter in the px function? The task must be done with the structure and functions listed.

Thanks in advance !

CodePudding user response:

If you are not allowed to pass n to the function, you can instead just loop to MAX and make sure that all unused coefficients are zero.

In other words, just initialize all elements of p to zero

POLYNOMIAL p = {.coef =  {0} };

and let the loop be:

j < MAX

BTW: Notice that you need return sum in the function.

Further the function degree is pretty unnecessary. Consider this:

double px(POLYNOMIAL p,double x)
{
    double sum=p.coef[0];
    double d = x;
    for(int j=1;j<MAX;j  )
    {
        sum =(double)p.coef[j]*d;
        d = d * x;
    }
    printf("%lf",sum);
    return sum;
}
  • Related