一元三次方程求解

来源:互联网 发布:软件招商加盟 编辑:程序博客网 时间:2024/04/27 15:24

Problem Description

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

Input

输入有多行测试数据,每行为四个系数a,b,c,d,输入以0 0 0 0结束。

Output

对于每组测试数据,输出一个三个实根(根与根之间留有空格),并精确到小数点后2位。

Sample Input

1 -5 -4 200 0 0 0

Sample Output

-2.00 2.00 5.00
#include<iostream>#include<cstdio>#include<cmath>using namespace std;double a,b,c,d;#define f(x) a*x*x*x+b*x*x+c*x+ddouble calculate(double ,double );int main(){//freopen("a.txt","r",stdin);while(cin>>a>>b>>c>>d&&(a||b||c||d)){double x1,x2;x1=(-2*b-sqrt(4*b*b-12*a*c))/(6*a); x2=(-2*b+sqrt(4*b*b-12*a*c))/(6*a);printf("%.2lf %.2lf %.2lf\n",calculate(-100,x1),calculate(x1,x2),calculate(x2,100));}return 0;}double calculate(double m,double n){double mid;if(f(m)==0) return m;if(f(n)==0) return n;while(n-m>1E-8) { mid=(m+n)/2;     if(f(mid)==0) return mid;     if(f(mid)>0&&f(m)<0||f(mid)<0&&f(m)>0) n=mid;     else m=mid;}return n;}


0 0
原创粉丝点击