📅  最后修改于: 2023-12-03 15:02:06.176000             🧑  作者: Mango
本程序可以输入二次方程$a\cdot x^2 + b\cdot x + c = 0$的系数$a, b, c$,然后利用求根公式计算并输出方程的两个根。
注意:当$b^2 - 4\cdot a\cdot c < 0$时,方程无实根,需要输出“无实根”。当$b^2 - 4\cdot a\cdot c = 0$时,方程有唯一实根$x = -b/(2\cdot a)$。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double delta = b * b - 4 * a * c;
if (delta < 0) {
System.out.println("无实根");
} else if (delta == 0) {
double x = -b / (2 * a);
System.out.println("x = " + x);
} else {
double x1 = (-b + Math.sqrt(delta)) / (2 * a);
double x2 = (-b - Math.sqrt(delta)) / (2 * a);
System.out.println("x1 = " + x1 + ", x2 = " + x2);
}
}
}