题目描述

有形如:ax3+bx2+cx+d=0 这样的一个一元三次方程。给出该方程中各项的系数(a,b,c,d 均为实数),并约定该方程存在三个不同实根(根的范围在-100至100之间),且根与根之差的绝对值>=1。要求由小到大依次在同一行输出这三个实根(根与根之间留有空格),并精确到小数点后2位。

 

输入

多组数据,一行,四个数

 

输出

三个根

 

样例输入

1 -5 -4 20

样例输出

-2.00 2.00 5.00

--正文

告诉你,根在-100 ~ 100间,2分找

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const double eps=0.0001;
double a,b,c,d;

double ans[5];
int sum;

double calc(double x)
{
    return a*x*x*x+b*x*x+c*x+d;
}

void find(double l,double r)
{
    if(r-l <= eps)
    {
        ans[++sum] = (l+r)/2;
        return;
    }
    double mid = (l+r)/2,tmp = calc(mid),tmpl = calc(l),tmpr = calc(r);
    if(abs(tmp) < eps)
    {
        ans[++sum] = mid;
        return;
    }
    if(tmp*tmpl < 0)
    {
        find(l,mid);
        return;
    }
    find(mid,r);
}

int main()
{
    while(scanf("%lf %lf %lf %lf",&a,&b,&c,&d) != EOF)
    {
        sum = 0;
        for(int i=-101;i<=101;i++)
        {
            double tmp1 = calc(i),tmp2 = calc(i+1);
            if(abs(tmp1) < eps)    ans[++sum] = i;
            else if(abs(tmp2) < eps)
            {
                ans[++sum] = i+1;
                i++;
            }
            else if(tmp1*tmp2 < 0)    find(i,i+1);
            if(sum == 3)    break;
        }
        sort(ans+1,ans+4);
        printf("%.2lf %.2lf %.2lf\n",ans[1],ans[2],ans[3]);
    }
    return 0;
}

 

posted on 2016-12-02 19:10  Crutain  阅读(269)  评论(0编辑  收藏  举报