題意:求f(x)=|a∗x3+b∗x2+c∗x+d|(L≤x≤R)的最大值
思路:對a進行分情況討論,a == 0,那麼就是一元二次方程求最值; a != 0,求導求極值點。
代碼如下:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
double a,b,c,d,l,r;
double fun(double x)
{
return fabs(a*x*x*x + b*x*x + c*x + d);
}
int main()
{
while(scanf("%lf%lf%lf%lf%lf%lf",&a,&b,&c,&d,&l,&r) != EOF)
{
double ans = max(fun(l),fun(r));
if(a == 0)
{
if(b != 0)
{
double temp = -c/b/2;
if(temp >= l && temp <= r) ans = max(ans,fun(temp));
}
}
else
{
double a1 = 3*a;
double b1 = 2*b;
double c1 = c;
double temp = b1*b1 - 4*a1*c1;
if(temp >= 0)
{
double x1 = (-b1 + sqrt(temp) )/2/a1;
double x2 = (-b1 - sqrt(temp) )/2/a1;
if(x1 >= l && x1 <= r) ans = max(ans,fun(x1));
if(x2 >= l && x2 <= r) ans = max(ans,fun(x2));
}
}
printf("%.2lf\n",ans);
}
return 0;
}