题解 | #计算一元二次方程#
计算一元二次方程
http://www.nowcoder.com/practice/7da524bb452441b2af7e64545c38dc26
public class Main{
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
Double a=sc.nextDouble();
Double b=sc.nextDouble();
Double c=sc.nextDouble();
if(a==0){
System.out.println("Not quadratic equation");
}else{
double x=Math.pow(b,2)-4*a*c;
double x1=0.0;
double x2=0.0;
if(x==0){
x1=x2=(-b)/(2*a);
System.out.printf("x1=x2=%.2f\n",x1);
}else if(x>0){
x1=(((-b)+Math.sqrt(x))/(2*a));
x2=(((-b)-Math.sqrt(x))/(2*a));
if(x1>x2){
double tmp=0.0;
tmp=x1;
x1=x2;
x2=tmp;
System.out.printf("x1=%.2f;x2=%.2f\n",x1,x2);
}else{
System.out.printf("x1=%.2f;x2=%.2f\n",x1,x2);
}
}else if(x<0){
double real=(-b)/(2*a);
if(b==0.00){
real=0.00;
}
double imag=Math.sqrt(-x)/(2*a);
System.out.printf("x1=%.2f-%.2fi;x2=%.2f+%.2fi\n",real,imag,real,imag);
}
}
}
}
}