添加两个多项式并正确显示结果

时间:2018-06-01 14:09:25

标签: c++ polynomial-math

我的代码非常简单:

    #include <cstdlib>
    #include <iostream>
    #include <string>
    #include <vector>
    #include <numeric>
    #include <cmath>

using namespace std;

int main() {

    int sizeOfPoly1;
    cout<<"Size of first polynomial: ";
    cin>>sizeOfPoly1;
    vector<int> poly1(sizeOfPoly1);
    cout<<"constant =";
    cin>>poly1[0];
    for (int i = 1; i <= (sizeOfPoly1-1); ++i)
    {
        cout<<"Insert x^"<<i<<": ";
        cin>>poly1[i];
    }

    int sizeOfPoly2;
    cout<<"Size of second polynomial: ";
    cin>>sizeOfPoly2;
    vector<int> poly2(sizeOfPoly2);
    cout<<"constant =";
    cin>>poly2[0];
    for (int i = 1; i <= (sizeOfPoly2-1); ++i)
    {
        cout<<"Insert x^"<<i<<": ";
        cin>>poly2[i];
    }


    int sizeOfResult;

    //verifies which polynomial has more elements and makes the result the size of the biggest one
    if (poly1.size() >= poly2.size())  sizeOfResult = poly1.size();
    else sizeOfResult = poly2.size();
    vector<int> result(sizeOfResult);


    for(int i = 0; i<sizeOfResult; ++i) { result[i] = poly1[i] + poly2[i]; }
    cout<<"Sum of the two polynomials: ";

    for(int i = 0; i<sizeOfResult; ++i)
    {
        switch(i){
            case 0:  cout<<result[i]<<" "; break;
            case 1:  cout<<result[i]<<"x"<<" "; break;
            default: cout<<result[i]<<"x^"<<i<<" "; break;
        }

    }


    return 0;
}

我想要做的是让用户输入多项式大小,然后为两者输入常数x ^ 1,x ^ 2等,然后返回两个多项式的和。此代码目前生成一些奇怪的东西: Sum of the two polynomials: 2 4x 6x^2 8x^3 1772060652x^4当一个多项式向量的元素多于另一个多项式向量时,如何防止此输出错误发生?

1 个答案:

答案 0 :(得分:3)

只需将它们设置为相同的尺寸并使用std::transform

const auto sizeOfResult = std::max( poly1.size(), poly2.size() );
poly1.resize( sizeOfResult );
poly2.resize( sizeOfResult );

vector<int> result(sizeOfResult);
std::transform( poly1.begin(), poly1.end(), poly2.begin(), result.begin(),
                []( int a, int b ) { return a+b; } );

这是简单的解决方案,但有轻微的开销。更有效的解决方案:

auto p = poly1.size() < poly2.size() ? std::tie( poly1, poly2 ) : std::tie( poly2, poly1 );
std::vector<int> result( std::get<1>( p ) );
for( size_t i = 0; i != std::get<0>( p ).size(); ++i )
    result[i] += std::get<0>( p )[i];

live example