
解法一
在[-100,100]大區(qū)間中遞進循環(huán),由于根與根之差的絕對值>=1,即在間隔為1的前開后閉區(qū)間里最多有一個根,從[i,i+1]中二分查找符合零點定理的解(題目中的提示即為零點定理,這里的閉區(qū)間是為了最后一個數(shù)100這個特殊情況)。
二分查找,精度設為0.001(也就是(high-low)<0.001才二分結(jié)束,小數(shù)點后第三位是唯一確定的,這時候就可以唯一確定一個精度為0.01的解了)
#include <stdio.h>
#define e(x) (d + (x) * (c + (x) * (b + a * (x))))
int main() {
double a, b, c, d, low, high, mid;
int index, resNum = 0;
scanf("%lf%lf%lf%lf",&a,&b,&c,&d);
for (index = -100; index < 100; index++) {
low = index;
high = index + 1;
if (e(low) == 0) { // 這里覆蓋不到100這個數(shù)
printf("%.2lf ",low);
resNum++;
}
else if (e(low)*e(high) < 0) {
while ((high-low) >= 0.001 ) { // 100這個特殊情況交由二分查找來解決
mid = (low + high) / 2.0;
if (e(low)*e(mid) <= 0) {
high = mid;
}
else {
low = mid;
}
}
printf("%.2lf ", low);
resNum++;
}
if (resNum == 3) break; // 節(jié)約時間
}
return 0;
}
解法二
暴力輪詢求解,通過小數(shù)點后兩位鎖定解所在的較小的一個范圍,然后再次循環(huán),間隔為0.0001,即可鎖定精度為0.01的解。
#include <stdio.h>
#define e(x) (d + (x) * (c + (x) * (b + a * (x))))
int main() {
double a, b, c, d, index_dec, index;
int s = 0;
scanf("%lf%lf%lf%lf", &a, &b, &c, &d);
for (index = -100; index < 100; index += 0.01) {
if (e(index)*e(index + 0.01) <= 0) {
for (index_dec = index; index_dec <= (index + 0.01); index_dec += 0.0001) {
if (e(index_dec)*e(index_dec + 0.0001) <= 0) {
printf("%.2lf ", index_dec);
s++;
if (s == 3) {
break; // 退出內(nèi)層For循環(huán)
break; // 退出外層For循環(huán)
}
}
}
}
}
return 0;
}