让求 f(x)=|a∗x3+b∗x2+c∗x+d|(L≤x≤R)的最大值
这个题目讨论a和b的值,如果a==0的话,那么这个方程就变成了一个一元二次方程,直接找端点和对称轴(如果对称轴在给定的区间内)处的函数值就行,如果a != 0,那么求导,求导之后判断二次方程的delta,如果delta小于等于0,说明是单调的,那么最值还是端点处取到,如果delta大于0, 那么就要比较两个极点(如果极点在给定的区间内)处的值和端点值的大小就行了。
/*************************************************************************
> File Name: math.cpp
> Author: Howe_Young
> Mail: 1013410795@qq.com
> Created Time: 2015年09月14日 星期一 20时18分44秒
************************************************************************/
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
using namespace std;
typedef long long ll;
double a, b, c, d, L, R;
const double eps = 1e-8;
double func(double x)
{
return fabs(a * x * x * x + b * x * x + c * x + d);
}
int sgn(double x)
{
if (fabs(x) < eps) return 0;
return x > 0 ? 1 : -1;
}
int main()
{
while (~scanf("%lf %lf %lf %lf %lf %lf", &a, &b, &c, &d, &L, &R))
{
double ans = max(func(L), func(R));
if (a == 0)
{
if (b != 0)
{
double t = -c / 2.0 / b;
if (sgn(t - L) > 0 && sgn(t - R) < 0)
ans = max(ans, func(t));
}
}
else
{
double delta = 4 * b * b - 12 * a * c;
if (delta > 0)
{
double x1 = (-2.0 * b - sqrt(delta)) / 6.0 / a;
double x2 = (-2.0 * b + sqrt(delta)) / 6.0 / a;
if (sgn(x1 - L) >= 0 && sgn(x1 - R) <= 0)
ans = max(ans, func(x1));
if (sgn(x2 - L) >= 0 && sgn(x2 - R) <= 0)
ans = max(ans, func(x2));
}
}
printf("%.2lf\n", ans);
}
return 0;
}
来源:https://www.cnblogs.com/Howe-Young/p/4808161.html