C++标准:制作一个多项式类,如何抑制用户输入的所有0系数
C++ std: Making a polynomial class, how to suppress all 0 coefficients that the user inputs?
现在我有了带整数系数的多项式类(几乎完成)。此类中的一个成员函数将多项式显示为:如果用户输入: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
它还确保您不会在第一个学期的输出中打印前导+
。
相关文章:
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何只允许用户输入正整数
- C++如何计算用户输入的数字中的偶数位数
- 通过for循环使用用户输入填充列表
- 这是我尝试让用户将值输入到数组中.然后将其隐藏为大量的星号
- 在C++中,我如何接受不同于同一行的用户输入
- 当用户超过按钮点击限制时报告
- Python中的for循环与C++有何不同
- Visual C++(VS2017)中用户定义的转换不明确
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 当用户键入分隔符时,停止getline()输入
- C++标准:制作一个多项式类,如何抑制用户输入的所有0系数