编程实现一元多项式的加法运算。第一个一元多项式A;第二个多项式B。以(0,0作为输入结束)。C++
时间: 2023-05-15 09:06:58 浏览: 104
一元稀疏多项式的加法运算
知道:
以下是一元多项式的加法运算的代码实现,其中A和B分别代表两个多项式:
#include <iostream>
#include <vector>
using namespace std;
struct Poly {
int coef; // 系数
int exp; // 指数
};
vector<Poly> addPoly(vector<Poly> A, vector<Poly> B) {
vector<Poly> C;
int i = 0, j = 0;
while (i < A.size() && j < B.size()) {
if (A[i].exp > B[j].exp) {
C.push_back(A[i]);
i++;
} else if (A[i].exp < B[j].exp) {
C.push_back(B[j]);
j++;
} else {
int sum = A[i].coef + B[j].coef;
if (sum != 0) {
Poly tmp;
tmp.coef = sum;
tmp.exp = A[i].exp;
C.push_back(tmp);
}
i++;
j++;
}
}
while (i < A.size()) {
C.push_back(A[i]);
i++;
}
while (j < B.size()) {
C.push_back(B[j]);
j++;
}
return C;
}
int main() {
vector<Poly> A, B;
Poly tmp;
cout << "请输入多项式A的系数和指数:" << endl;
while (cin >> tmp.coef >> tmp.exp) {
if (tmp.coef == 0 && tmp.exp == 0) break;
A.push_back(tmp);
}
cout << "请输入多项式B的系数和指数:" << endl;
while (cin >> tmp.coef >> tmp.exp) {
if (tmp.coef == 0 && tmp.exp == 0) break;
B.push_back(tmp);
}
vector<Poly> C = addPoly(A, B);
cout << "多项式A + 多项式B = ";
for (int i = 0; i < C.size(); i++) {
cout << C[i].coef << "x^" << C[i].exp;
if (i != C.size() - 1) cout << " + ";
}
cout << endl;
return 0;
}
希望这个代码能够帮到你!
阅读全文