首先,要明确题目信息,f(x1) * f(x2) < 0, 则一定存在实数根在区间(x1, x2)。且所有的根都在[-100, 100)之间。根与根的绝对值之差 >= 1
那么,我们是否可以找到所有的x1 和 x2 呢? 当然可以。
根的取值范围这么小 (每一个区间都枚举一次的话也只有200个区间),那么我们当然就愉快的枚举啊!
在 [-100, 100)的区间里面枚举符合条件的 x1, x2。然后再对该区间进行二分查找(二分赛高!)
#include <bits/stdc++.h>
using namespace std;
#define du double
du a, b, c, d;
int now;
du ans;
inline du cac(du x){ //x 对应的 f 的值
return a * x * x * x + b * x * x + c * x + d;
}
inline void search(du l, du r){
if(now == 3)return;
if(r - l <= 0.001){//差这么小,已经可以说是相等了。直接输出
printf("%.2lf ", l);
now++;
return ;
}
du mid = l + (r - l) / 2;
du ansl, ansr;
ansl = cac(l) * cac(mid);
ansr = cac(mid) * cac(r);
if(cac(r) == 0){ //是否存在端点为根的情况?
printf("%.2lf ", r);
now++;
}
if(cac(mid) == 0){
printf("%.2lf ", mid);
now++;
}
if(ansl < 0)
search(l, mid);//继续二分搜索, 注意不一定只有一个根
else if(ansr < 0)search(mid, r);
return;
}
int main(){
freopen("count.in", "r", stdin);
freopen("count.out", "w", stdout);
cin >> a >> b >> c >> d;
for(du i = -100.0; i <= 99; i++){
if(cac(i) * cac(i + 1) <= 0)//枚举符合条件的区间
search(i, i + 1);
}
return 0;
}
来源:https://www.cnblogs.com/wondering-world/p/12641543.html