C++ C++;std:制作一个多项式类,如何抑制用户输入的所有0系数?
现在我有了一个整数系数的多项式类(几乎完成了)。 此类中的一个成员函数将多项式显示为: 如果用户输入: 1, -2, 0, 4 然后函数将其打印为“p(x)=1+-2x+0x^2+4x^3” 这不是预期的,因为我想消除0x^2项,因为它的系数为0。。 它应该是:“p(x)=1+-2x+4x^3” 现在我的“打印”成员函数在这里:C++ C++;std:制作一个多项式类,如何抑制用户输入的所有0系数?,c++,C++,现在我有了一个整数系数的多项式类(几乎完成了)。 此类中的一个成员函数将多项式显示为: 如果用户输入: 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 for
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;
}
void多项式::print()常量
{
//以最简单的形式打印出多项式
string plus;//除第一个元素外,每个元素前面都有加号
加上“+”;
int k=0;//与k相同
不能将函数更改为如下所示:
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 = "+";
}
}
}
进入:
它还确保您不会在第一个学期输出中打印前导的+
。使用“如果”语句。和-12345
作为停止的神奇序列?哎哟!我想你也应该处理负系数。形式1+-2x
不太好看。谢谢;@John,我怎么写这个if语句?我已经认真考虑了好几个小时了…@roshinichi?如果(系数[I]!=0)
呢?
x+-3x^2
x-3x^2