S
S
Silence2019-01-24 13:45:39
C++ / C#
Silence, 2019-01-24 13:45:39

How to make a function that converts the degree and coefficients of a polynomial into a finished equation?

There are, for example, such fields in the class as:

int degree; //степень многочлена
double *koef; //на массив коэффициентов многочлена

How to make a function transforming (returning) from for example:
degree=3;
koef[degree+1]=[9,8,-7,6]
into this equation:
9*x*x*x+8*x*x-7*x+6

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Egor, 2019-01-24
@Adrikk

#include <iostream>

void printPolynom(double* coefs, int degree, std::ostream& os)
{
    static const char VAR = 'x';
    
    bool first = true;  
    for (int i = degree; i >= 0; --i) {
        double coef = *coefs;
        coefs++;
        
        if (!first && coef > 0.0) {
            os << "+";
        }
        first = false;
        
        os << coef;
        for (int j = 0; j < i; ++j) 
            os << '*' << VAR;
    }
}

int main()
{
   const int degree = 3;
   double coefs[degree + 1] = { 9, 3, 12, -1 };
   printPolynom(coefs, degree, std::cout);
   
   std::cout << "\nDone";
   return 0;
}

R
res2001, 2019-01-24
@res2001

You just need to form a string.
In the loop through the koef array, run:
1.if the coefficient is not 0:
1.1.print the coefficient itself from the array
1.2.If the coefficient is not the last: print the string "x^" + str(degree - i)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question