题目描述
求方程 的根,用三个函数分别求当b^2-4ac大于0、等于0、和小于0时的根,并输出结果。从主函数输入a、b、c的值。
输入格式
a b c
输出格式
x1=? x2=?
样例输入
4 1 1
样例输出
x1=-0.125+0.484i x2=-0.125-0.484i
分析:
- 注意输出的格式和计算过程的精度
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
double delta = b * b - 4 * a * c;
if (delta > 0) {
twoRoots(a, b, delta);
} else if (delta == 0) {
oneRoot(a, b, delta);
} else {
complexRoots(a, b, delta);
}
}
// 两个实根
public static void twoRoots(double a, double b, double delta) {
double x1 = (-b - Math.sqrt(delta)) / (2 * a);
double x2 = (-b + Math.sqrt(delta)) / (2 * a);
System.out.printf("x1=%.3f x2=%.3f", x1, x2);
}
// 一个实根
public static void oneRoot(double a, double b, double delta) {
double x = -b / (2 * a);
System.out.printf("x1=%.3f x2=%.3f", x, x);
}
// 共轭复根
public static void complexRoots(double a, double b, double delta) {
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-delta) / (2 * a);
System.out.printf("x1=%.3f+%.3fi x2=%.3f-%.3fi", realPart, imaginaryPart, realPart, imaginaryPart);
}
}