求方程 的根,用三個函式分別求當b^2-4ac大於0、等於0、和小於0時的根,並輸出結果。從主函式輸入a、b、c的值。
解題思路:
一元二次方程
ax²+bx+c=0(a≠0)
其求根依據判定式△的取值為三種( △=b²-4ac )
1. △>0,方程有兩個不相等的實數根;
x1=[-b+√(△)]/2a;
//( △=b²-4ac )
x2=[-b-√(△)]/2a;
2. △=0,方程有兩個相等的實數根;
x1=x2=[-b+√(△)]/2a= -b/2a ;
3. △<0,方程無實數根,但有2個共軛復根。
x1=[-b+√(△)*i]/2a;
//( △=b²-4ac )
x2=[-b-√(△)*i]/2a;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
int c=sc.nextInt();
if(b*b-4*a*c>0){
double x=(double)-b/(2*a);
double y=(double)(Math.sqrt(b*b-4*a*c)/(2*a));
String str=String.format("%.3f", x);
String result=String.format("%.3f", y);
System.out.println("x1="+str+"+"+result+"i x2="+str+"-"+result+"i");
}
else if(b*b-4*a*c==0){
double x=(double)-b/(2*a);
String str=String.format("%.3f", x);
System.out.println("x1="+str+" x2="+str);
}
else{
double x=(double)-b/(2*a);
double y=(double)(Math.sqrt(4*a*c-b*b)/(2*a));
String str=String.format("%.3f", x);
String result=String.format("%.3f", y);
System.out.println("x1="+str+"+"+result+"i x2="+str+"-"+result+"i");
}
}
}