编写程序,定义一个静态方法,求出一元二次方程axx+b*x+c=0的二个实数根,计算二个实数根可使用Math类中的Sqrt()方法来计算开方。在main方法中,要求通过键盘输入方程a、b、c的值,并判断是否有实根,如果有的话求出实根
时间: 2024-05-27 13:14:49 浏览: 47
。Java代码如下:
import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of a: ");
double a = input.nextDouble();
System.out.print("Enter the value of b: ");
double b = input.nextDouble();
System.out.print("Enter the value of c: ");
double c = input.nextDouble();
double[] roots = findRoots(a, b, c);
if (roots == null) {
System.out.println("The equation has no real roots.");
} else if (roots.length == 1) {
System.out.println("The equation has one real root: " + roots[0]);
} else {
System.out.println("The equation has two real roots: " + roots[0] + " and " + roots[1]);
}
}
public static double[] findRoots(double a, double b, double c) {
double delta = b * b - 4 * a * c;
if (delta < 0) {
return null;
} else if (delta == 0) {
double[] roots = new double[1];
roots[0] = -b / (2 * a);
return roots;
} else {
double[] roots = new double[2];
roots[0] = (-b + Math.sqrt(delta)) / (2 * a);
roots[1] = (-b - Math.sqrt(delta)) / (2 * a);
return roots;
}
}
}
阅读全文