P1024 [NOIP2001 提高组] 一元三次方程求解 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
值得复习
二分代码:
#include<iostream>
using namespace std;
int cnt;
double a, b, c, d;
double f(double x)
{
return a * x * x * x + b * x * x + c * x + d;
}
int main()
{
double l, r , m, x1, x2;
int i;
scanf("%lf%lf%lf%lf", &a, &b, &c, &d);
for (i = -100; i < 100; i++)
{
l = i;
r = i + 1;
x1 = f(l);
x2 = f(r);
if(!x1)
{
printf("%.2lf ", l);
cnt++;
} //判断左端点,是零点直接输出
//不能判断右端点,会重复。
if(x1 * x2 < 0) //区间内有根
{
while(r - l >= 0.001)
{
m = (l + r) / 2;
if (f(m) * f(r) <= 0) l = m;
else r = m;
}
printf("%.2lf ", r);
cnt++;
}
if (cnt == 3) break;
}
return 0;
}
暴力枚举代码:
#include <iostream>
using namespace std;
int main()
{
double a, b, c, d;
scanf("%lf%lf%lf%lf", &a, &b, &c, &d);
for (double i = -100; i <= 100; i += 0.001)
{
double j = i + 0.001;
double y1 = a * i * i * i + b * i * i + c * i + d;
double y2 = a * j * j * j + b * j * j + c * j + d;
if (y1 >= 0 && y2 <= 0 || y1 <= 0 && y2 >= 0)
{
double x = (i + j) / 2;
printf("%.2lf ", x);
}
}
return 0;
}