本题是一个数学方程问题
由题可得:三个不同的根之间的距离最小为1,所以我们可以把每个区间1当作一份,在这个区间中进行二分,因为题目要求精度为0.01,所以可以控制精度在两个端点差小于0.001时停止二分,总共循环200次即可。
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int N = 5 * 1e5 + 10;
//typedef long long LL;
double a, b, c, d;
double f(double x)
{
return a * x * x * x + b * x * x + c * x + d;
}
void BinarySearch(double l, double r)
{
double mid;
if (f(l) == 0)
cout << fixed << setprecision(2) << l << " ";
else if (f(l) * f(r) < 0)
{
while (r - l >= 0.001)//求根时要控制精度
{
mid = (l + r) / 2;
if (f(l) * f(mid) <= 0)
r = mid;
else
l = mid;
}
cout << fixed << setprecision(2) << l << " ";
}
}
int main()
{
cin >> a >> b >> c >> d;
for (int i = -100; i <= 100; i += 1)
{
BinarySearch(i, i + 1);
}
return 0;
}
当然,我们还有一个更直接的方法,暴力枚举
上代码:
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int N = 5 * 1e5 + 10;
//typedef long long LL;
double a, b, c, d;
double f(double x)
{
return a * x * x * x + b * x * x + c * x + d;
}
int main()
{
int num = 0;
cin >> a >> b >> c >> d;
for (double i=-100;i<=100;i+=0.001)//一定要控制精度
{
double j = i + 0.001;
if (f(i) * f(j) < 0)
{
cout << fixed << setprecision(2) << i << ' ';
++num;
}
if (num == 3)break;
}
return 0;
}