3、Polynomial GetPoly(); 设计函数功能:从标准输入中获得多项式可以把输入独立成一个函数,当输入一个新的多项式时可以直接调用,也可将该部分操作放在main函数中。
时间: 2023-05-27 13:05:58 浏览: 41
以下是一个示例代码,可供参考:
```
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Term {
int coef; // 系数
int exp; // 指数
};
class Polynomial {
public:
void AddTerm(int coef, int exp) {
terms.push_back({coef, exp});
}
void Print() const {
for (int i = 0; i < terms.size(); i++) {
if (i != 0) {
cout << " + ";
}
cout << terms[i].coef << "x^" << terms[i].exp;
}
cout << endl;
}
private:
vector<Term> terms;
};
Polynomial GetPoly() {
Polynomial poly;
string input;
cout << "请输入多项式,以“q”结束:" << endl;
while (true) {
cin >> input;
if (input == "q") {
break;
}
int coef, exp;
sscanf(input.c_str(), "%dx^%d", &coef, &exp);
poly.AddTerm(coef, exp);
}
return poly;
}
int main() {
Polynomial poly = GetPoly();
cout << "多项式为:";
poly.Print();
return 0;
}
```
该代码中,GetPoly函数用于从标准输入中获取多项式。在函数内部,首先输出提示信息,然后进入循环。每次循环中,从标准输入中读取一行字符串,如果字符串为“q”则退出循环,否则将该字符串解析成系数和指数,再将其作为一项添加到多项式中。最终返回多项式对象。
在主函数中,调用GetPoly函数获取多项式对象,然后调用Print函数输出多项式。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)