目前我正在做一个项目(即创建一个多项式类)并且我已经实现了“加减除等”方法。但是我坚持使用一种方法将 3x^1-2x^4 这样的字符串传递给 0 3 0 0 4 这样的系数 vector 。
代码如下:
string s;
cin >> s;
istringstream iss(s);
double coeff;
char x, sym;
int degree;
vector<double> coefficients;
int i = 0;
while (iss >> coeff >> x >> sym >> degree) {
//if (sign == '-') coeff *= -1;
if (degree == i) {
cout << coeff << i;
coefficients.push_back(coeff);
++i;
}
else {
for (int j = i; j < degree; ++j) {
coefficients.push_back(0);
}
coefficients.push_back(coeff);
++i;
}
Polynomial p (coefficients);
p.write();
顺便说一下,我正在使用 istringstream,但不幸的是,由于某种原因它似乎不起作用而且我无法弄清楚我的代码有什么问题? “多项式 p(系数)”最后似乎是空的。 也许是构造函数的问题?
Polynomial::Polynomial (const vector<double>& coeff)
: coeff(coeff)
{}
// Constructor from string.
Polynomial::Polynomial (const string& spoly) : spoly(spoly) {}
提前致谢!
最佳答案
是的,最终我发现了问题所在。我在 Mac 上编译,但当我切换到 Linux 时,它运行完美。因此,Mac 的解决方案是编写
cout << endl;
在代码块的末尾。
关于c++ - 使用 istringstream c++ 提取多项式的系数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49495294/