令一元二次方程判别式: b2 - 4ac为变量P
**当P > 0时:**
x1 = (-b+sqrt(P)) / 2a
x1 = (-b-sqrt(P)) / 2a
**当P = 0时:**
x1 = x2 = -b / 2a
**当P < 0时,一元二次方程无解当存在共轭复数:**
x1 = -b/2a + sqrt(-P)×i
x1 = -b/2a - sqrt(-P)×i
(注:i为虚数单位,如果高中数学好的话,应该知道)
**代码块**:
```java
import java.util.Scanner;
public class 一元二次方程 {
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 temp = b*b-4*a*c;
double x1=0, x2=0;
if(temp > 0){
x1 = (-b+Math.sqrt(temp))/(2*a);
x2 = (-b-Math.sqrt(temp))/(2*a);
}else if(temp == 0){
x1 = x2 = -b/(2*a);
}else{
double x11 = (-b)/(2*a);
double x12 = (Math.sqrt(-temp))/(2*a);
System.out.print
("x1="+String.format("%.3f", x11)+"+"+String.format("%.3fi", x12));
System.out.print
(" x2="+String.format("%.3f", x11)+"-"+String.format("%.3fi", x12));
return;
}
System.out.println
("x1="+String.format("%.3f",x1)+" x2="+String.format("%.3f",x2));
}
}
```
0.0分
1 人评分