简体   繁体   中英

C++ std: Making a polynomial class, how to suppress all 0 coefficients that the user inputs?

Now I have my Polynomial class (almost done) with integer coefficients. One of the member functions in this class displays the polynomial as: if the user inputs: 1, -2, 0, 4 then the function prints it as "p(x)=1+-2x+0x^2+4x^3" which is not expected because I want to eliminate the 0x^2 term since it has a 0 coefficient.. it's supposed to be: "p(x)=1+-2x+4x^3" instead.

Now my "print" member function is here:

void Polynomial::print() const
{
    //prints out the polynomial in the simplest form

    string plus;//plus sign in front of every element except the first element
    plus="+";
    int k=0;//same as k
    cout<<coefficient[0];
    for(int i=1;i<coefficient.size();i++)
    {
        if(coefficient[i]==-12345)
            break;//where -12345 is the key to enter to stop inputting 
        cout<<plus<<coefficient[i]<<"x";

        if(coefficient[i]!=-12345)
        {
            k++;
        }
        if(k>1)
        {
            cout<<"^"<<k;
        }
    }

    cout<<endl;
    return;
}

what else should I add to eliminate the 0 coefficient ?

Thanks a lot!

Change your function to be something like the following:

void Polynomial::print() const {
    // Ignore initial pluses, set to "+" when first term is output.

    string plus = "";

    if (coefficient[0] != 0) {
        // Output initial x^0 coefficient.

        cout << coefficient[0];

        // Ensure future positives have sign.

        plus = "+";
    }

    for (int i = 1; i < coefficient.size(); i++) {
        // Only for non-zero coefficients.

        if (coefficient[i] != 0) {
            // Only output + for positives.

            if (coefficient[i] > 0) {
                cout << plus;

            // Output coefficient and x.

            cout << coefficient[i] << "x";

            // Output exponent if 2 or more.

            if (i > 1)
                cout << "^" << i;

            // Ensure future positives have sign.

            plus = "+";
        }
    }
}

This correctly ignores zero terms and gets rid of the annoying +- sequences where you just need - , such as turning:

x+-3x^2

into:

x-3x^2

It also ensures you don't print a leading + on the first term output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM