此代码应输出2个不同多项式的最大系数,但如果第一个大于第二个,则无法正确编译。
因此,如果第一个多项式是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 << ".\n\nPlease 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 << ".\n\nThe 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 << ".\n\nThe 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;
}
答案 0 :(得分:0)
假设你的coefficient
向量只运行到多项式最高幂的索引(即如果x^3
是最高幂,它有4个元素),尝试用
int Polynomial::Coefficient(int k) const{
if (k < coefficient.size())
return coefficient[k];
else
return 0;
}