c++一元多项式计算器
时间: 2023-11-24 13:51:51 浏览: 95
duoxiangshi.rar_duoxiangshi_一元多项式计算器
以下是一个简单的C++一元多项式计算器的实现,可以实现多项式的加减乘和求根功能:
```c++
#include <iostream>
#include <cmath>
using namespace std;
const int MAXN = 1005;
const double EPS = 1e-8;
struct Poly {
double coef[MAXN];
int deg;
Poly() {
memset(coef, 0, sizeof(coef));
deg = 0;
}
};
Poly read_poly() {
Poly p;
cin >> p.deg;
for (int i = p.deg; i >= 0; i--) {
cin >> p.coef[i];
}
return p;
}
void print_poly(Poly p) {
cout << p.deg;
for (int i = p.deg; i >= 0; i--) {
cout << " " << p.coef[i];
}
cout << endl;
}
Poly add_poly(Poly a, Poly b) {
Poly c;
c.deg = max(a.deg, b.deg);
for (int i = c.deg; i >= 0; i--) {
c.coef[i] = a.coef[i] + b.coef[i];
}
while (c.deg > 0 && fabs(c.coef[c.deg]) < EPS) {
c.deg--;
}
return c;
}
Poly sub_poly(Poly a, Poly b) {
Poly c;
c.deg = max(a.deg, b.deg);
for (int i = c.deg; i >= 0; i--) {
c.coef[i] = a.coef[i] - b.coef[i];
}
while (c.deg > 0 && fabs(c.coef[c.deg]) < EPS) {
c.deg--;
}
return c;
}
Poly mul_poly(Poly a, Poly b) {
Poly c;
c.deg = a.deg + b.deg;
for (int i = 0; i <= a.deg; i++) {
for (int j = 0; j <= b.deg; j++) {
c.coef[i+j] += a.coef[i] * b.coef[j];
}
}
while (c.deg > 0 && fabs(c.coef[c.deg]) < EPS) {
c.deg--;
}
return c;
}
double calc_poly(Poly p, double x) {
double ans = 0;
for (int i = p.deg; i >= 0; i--) {
ans = ans * x + p.coef[i];
}
return ans;
}
double solve_poly(Poly p, double l, double r) {
double mid;
while (r - l > EPS) {
mid = (l + r) / 2;
if (calc_poly(p, mid) > 0) {
l = mid;
} else {
r = mid;
}
}
return mid;
}
int main() {
Poly a = read_poly();
Poly b = read_poly();
Poly c = add_poly(a, b);
Poly d = sub_poly(a, b);
Poly e = mul_poly(a, b);
print_poly(c);
print_poly(d);
print_poly(e);
double root = solve_poly(e, -100, 100);
printf("%.2f\n", root);
printf("%.2f\n", calc_poly(e, 1.23));
printf("%.2f\n", calc_poly(e, -4.56));
return 0;
}
```
阅读全文