C++标准:制作一个多项式类,如何抑制用户输入的所有0系数

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

本文关键字:用户 何抑制 输入 系数 多项式 标准 一个 C++      更新时间:2023-10-16

现在我有了带整数系数的多项式类(几乎完成)。此类中的一个成员函数将多项式显示为:如果用户输入:1,-2,0,4则函数将其打印为"p(x)=1+-2x+0x^2+4x^3"这是不期望的,因为我想消除0x^2项,因为它有一个0系数。。它应该是:"p(x)=1+-2x+4x^3"。

现在我的"打印"成员功能在这里:

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

我还应该加什么来消除0系数?

非常感谢!

将您的函数更改为如下所示:

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 = "+";
        }
    }
}

这正确地忽略了零项,并且消除了只需要-的恼人的+-序列,例如车削:

x+-3x^2

进入:

x-3x^2

它还确保您不会在第一个学期的输出中打印前导+