1. 程式人生 > >求方程ax2+bx+c=0的實數根

求方程ax2+bx+c=0的實數根

求方程ax2+bx+c=0的實數根。a, b, c由鍵盤輸入, a!=0。若只有一個實數根(b2-4ac=0)則只輸出x1,若無實數根(b2-4ac<0)則輸出Error。

輸入

  2.5 7.5 1.0

輸出

(注意等號前面後面都有一個空格)

(注意等號前面後面都有一個空格)

  x1 = -0.139853

x2 = -2.860147

import java.util.Scanner;

public class ALGO160 {
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	double a = sc.nextDouble();
	double b = sc.nextDouble();
	double c = sc.nextDouble();
	double d = b*b-4*a*c;
	double e = -b/(2*a);
	if(d<0){
		System.out.println("Error");
	}else{
		if(d>0){
			double x1 = e+Math.sqrt(d)/(2*a);
		    double x2 = e- Math.sqrt(d)/(2*a);
		    System.out.println("x1"+" = "+String.format("%.6f", x1));
		    System.out.println("x2"+" = "+String.format("%.6f", x2));
		}else {
			System.out.println("x1"+" = "+String.format("%.6f", e));
		}
	}
}
}