求一元二次方程a

求一元二次方程a

http://acm.ocrosoft.com/problem.php?id=1015

题目描述

求一元二次方程a*x2 + b*x + c = 0的根。系数a、b、c为浮点数,其值在运行时由键盘输入。须判定Δ(即三角形的判别式)的情形。

输入

有多组测试数据,每组测试数据有三个浮点数,分别为a,b,c。输入直到文件尾(!=EOF).

输出

每组测试数据输出一行。若有不同根,根按从大到小输出。相同根需输出两次。

样例输入

5 10 5
4 10 4
5.9 10 5.9
-5 -9 4

样例输出

the roots are -1.000000 and -1.000000
the roots are -0.500000 and -2.000000
delta is negative, no root.
the roots are 0.368858 and -2.168858

定义小数尽量使用double进行定义

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <iomanip>
using namespace std; int main()
{
double a,b,c;
double n;
double x1,x2;
while(scanf("%lf%lf%lf",&a,&b,&c)!=EOF)
{
n=b*b-4*a*c;
x1=(-b-sqrt(n))/(2*a);
x2=(-b+sqrt(n))/(2*a);
cout<<setiosflags(ios::fixed)<<setprecision(6);
if(n<0)
cout<<"delta is negative, no root."<<endl;
else if(n>=0){ if(x1>=x2)
cout<<"the roots are "<<x1<<" "<<"and"<<" "<<x2<<endl;
else
cout<<"the roots are "<<x2<<" "<<"and"<<" "<<x1<<endl;
}
}
return 0;
}

  

05-07 15:25