将两个多项式与向量系数进行比较C++

Comparing two polynomials with vector's coefficients C++

本文关键字:C++ 比较 向量 多项式 两个      更新时间:2023-10-16

此代码应该输出两个不同多项式的最大系数,但如果第一个大于第二个,则无法正确编译。

所以,如果第一个多项式是1-2x+4x^3,第二个多项式是-x+5x^2-3x^6。它将起作用,因为第二个多项式比第一个多项式大。

每当第一个多项式大于第二个时,它就会发布"矢量下标超出范围"错误

class Polynomial {
public:
Polynomial();
Polynomial(const vector<int>& coeffs);
int Degree() const;
int Coefficient(int k) const;
void print() const;
private:
vector<int>coefficient;
int main(){
//Variable and vector for inputs
vector<int> coefficient;
int input = 0;
//Welcome message
cout << "Welcome! Please input the coefficients of the first polynomial p(x).nWhen you are finished, enter -12345.n";
//While loop - if input isn't -12345, put the input into coefficient.
while (input != -12345){
    cin >> input;
    coefficient.push_back(input);
}
//Deletes -12345
coefficient.pop_back();
//Puts coefficient values into constructor
Polynomial first(coefficient);
//Prints first polynomial
cout << "nYour first polynomial is p(x) = ";
first.print();
//Prints degrees of first polynomial
cout << ".np(x) has degree " << first.Degree();
int degree1 = first.Degree();
//Prints transformation of first polynomial
cout << ".nThe transform of p(x) is ";
first.Transform();
//clears the values in coefficient for second polynomial inputs.
coefficient.clear();
//Inputs the second polynomial's coefficients.
cout << ".nnPlease input the coefficients of the second polynomial q(x).n";
//Had to use do-while because while loop wouldn't work.
do {
    cin >> input;
    coefficient.push_back(input);
} while (input != -12345);
//Deletes -12345
coefficient.pop_back();
//Puts coefficients into second polynomial
Polynomial second(coefficient);
//Prints second polynomial
cout << "nYour second polynomial is q(x) = ";
second.print();
cout << ".nq(x) has degree " << second.Degree();
int degree2 = second.Degree();
if (degree1 > degree2){
    cout << ".nnThe coefficient of x^" << degree1 << " in p(x) is " << first.Coefficient(degree1);
    cout << ".nThe coefficient of x^" << degree1 << " in q(x) is " << second.Coefficient(degree1);
}
else{
    cout << ".nnThe coefficient of x^" << degree2 << " in p(x) is " << first.Coefficient(degree2);
    cout << ".nThe coefficient of x^" << degree2 << " in q(x) is " << second.Coefficient(degree2);
}
int Polynomial::Degree() const{
int number = 0;
for (size_t i = 0, size = coefficient.size(); i < size; i++){
    if (coefficient[i] != 0)
        number = i;
}
return number;
}
int Polynomial::Coefficient(int k) const{
if (coefficient[k] != 0)
    return coefficient[k];
else
    return 0;
}

假设coefficient向量只达到多项式的最高幂的索引(即,如果x^3是最高幂,则它有4个元素),请尝试用替换函数

int Polynomial::Coefficient(int k) const{
    if (k < coefficient.size())
        return coefficient[k];
    else
        return 0;
}