第1条题解
2024-10-29 16:15:38
发布于:广东
1阅读
0回复
0点赞
这一道题并不难代码如下。
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
double f(double a, double b, double c, double d, double x) {
return a * x * x * x + b * x * x + c * x + d;
}
double findRoot(double a, double b, double c, double d, double left, double right) {
double mid;
while (right - left > 1e-5) {
mid = (left + right) / 2;
if (f(a, b, c, d, mid) * f(a, b, c, d, left) < 0) {
right = mid;
} else {
left = mid;
}
}
return mid;
}
int main() {
double a, b, c, d;
cin >> a >> b >> c >> d;
vector<double> roots;
for (int i = -100; i <= 100; ++i) {
double left = i;
double right = i + 1;
if (f(a, b, c, d, left) == 0) {
roots.push_back(left);
} else if (f(a, b, c, d, left) * f(a, b, c, d, right) < 0) {
roots.push_back(findRoot(a, b, c, d, left, right));
}
}
sort(roots.begin(), roots.end());
for (int i = 0; i < roots.size(); ++i) {
cout << fixed << setprecision(2) << roots[i];
if (i < roots.size() - 1) {
cout << " ";
}
}
cout << endl;
return 0;
}
点个赞吧
这里空空如也
有帮助,赞一个