洛谷P1024 一元三次方程的纯代码题解
程序员文章站
2022-05-09 10:03:31
...
一个入门题第一下给我WA掉了不愧是我
一检查发现是函数传double参数时习惯性写成了int我原地嘤嘤嘤
这题,注意精度,没了
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
#define eps 1e-4
double a, b, c, d;
double f(double x)
{
return a * x * x * x + b * x * x + c * x + d;
}
int main()
{
scanf("%lf%lf%lf%lf", &a, &b, &c, &d);
for(int i = -100; i <= 100; i ++)
{
double l = i, r = i + 1;
double mid;
if(fabs(f(l)) < eps) printf("%.2lf ", l);
else if(fabs(f(r)) < eps) continue;
else if(f(l) * f(r) < 0)
{
while(r - l > eps)
{
//printf("f(l) is %.2lf, f(r) is %.2lf\n", f(l), f(r));
mid = (l + r) / 2;
if(f(mid) * f(r) > 0) r = mid;
else l = mid;
//printf("l is %.2lf, r is %.2lf\n", l, r);
}
printf("%.2lf ", l);
}
}
printf("\n");
return 0;
}