[英]C++ polynomial class, print member function not working well with the power
我正在對兩個多項式進行一些基本運算的多項式類。 除打印功能外,我的其他成員功能運行良好。 這是我的打印成員函數:
void Polynomial::print() const
{
string plus;//plus is the plus sign in front of every element except the first element
plus="+";
int k=0;//k is the power of the each element in the polynomial
if(coefficient[0]!=0)
cout<<coefficient[0];
for(int i=1;i<coefficient.size();i++)
{
if(coefficient[i]==-1234)
break;
if(coefficient[i]==0)
{
k++;
}
else if(coefficient[i]==1)
{
if(coefficient[i]>=1)
cout<<plus;
cout<<"x";
k++;
}
else if(coefficient[i]==-1)
{
if(coefficient[i]>=1)
cout<<plus;
cout<<"-x";
k++;
}
else
{
if(coefficient[i]>=1)
cout<<plus;
cout<<coefficient[i]<<"x";
if(coefficient[i]!=-1234)
{
k++;
}
else
break;
if(k>1)
{
cout<<"^"<<k;
}
}
}
cout<<endl;
return;
}
現在,如果用戶輸入:1 2 3 1多項式打印為:1 + 2x + 3x ^ 2 + x多項式中的第4個項的k(冪)不為4。小時...仍然不知道哪里出了問題。 謝謝你的幫助!!!
您的for循環應如下所示。 當系數為1或-1時,您不打印功率:
for(int i=1;i<coefficient.size();i++)
{
if(coefficient[i]==-1234)
break;
if(coefficient[i]==0)
{
k++;
}
else if(coefficient[i]==1)
{
if(coefficient[i]>=1)
cout<<plus;
cout<<"x";
k++;
if(k>1)
{
cout<<"^"<<k;
}
}
else if(coefficient[i]==-1)
{
if(coefficient[i]>=1)
cout<<plus;
cout<<"-x";
k++;
if(k>1)
{
cout<<"^"<<k;
}
}
else
{
if(coefficient[i]>=1)
cout<<plus;
cout<<coefficient[i]<<"x";
if(coefficient[i]!=-1234)
{
k++;
}
else
break;
if(k>1)
{
cout<<"^"<<k;
}
}
}
問題是您要輸入該塊的最后1
:
else if (coefficient[i] == 1)
{
if (coefficient[i] >= 1)
cout << plus;
cout << "x";
k++;
}
破壞了x^power
部分。
可能的解決方案可能是:
void print()
{
string plus;
plus = "+";
int k = 0;
if (coefficient[0] != 0)
cout << coefficient[0];
for (int i = 1; i<coefficient.size(); i++)
{
if (coefficient[i] == -1234)
break;
if (coefficient[i] == 0)
{
k++;
}
else if (coefficient[i] == 1 && i == 1 /* This prevents entering here afterwards */)
{
if (coefficient[i] >= 1)
cout << plus;
cout << "x";
k++;
}
else if (coefficient[i] == -1 && i == 1 /* This prevents entering here afterwards */)
{
if (coefficient[i] >= 1)
cout << plus;
cout << "-x";
k++;
}
else
{
if (coefficient[i] >= 1)
cout << plus;
cout << coefficient[i] << "x";
if (coefficient[i] != -1234)
{
k++;
}
else
break;
if (k>1)
{
cout << "^" << k;
}
}
}
cout << endl;
}
這實際上歸結為您對如何打印和格式化多項式感到滿意。
以下內容可能會有所幫助:
void print_polynom(const std::vector<int>& coeffs)
{
const char* plus = "";
const char* space = "";
for (std::size_t i = 0; i != coeffs.size(); ++i) {
if (coeffs[i] == 0) {
continue;
}
if (coeffs[i] > 0) {
std::cout << space << plus << space;
} else {
std::cout << space << "-" << space;
}
plus = "+";
space = " ";
if (i == 0 || std::abs(coeffs[i]) != 1) { // to avoid to print 1x^k
std::cout << std::abs(coeffs[i]);
}
if (i == 0) {
continue;
}
std::cout << "x";
if (i == 1) { // not print x^1
continue;
}
std::cout << "^" << i;
}
std::cout << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.