JAVA利用公式x1 = (-b + sqrt(b*b-4*a*c))/(2*a), x2 = (-b - sqrt(b*b-4*a*c))/(2*a)求一元二次方程ax2 + bx + c =0的根,其中a不等于0。
时间: 2023-03-24 10:02:01 浏览: 180
用Java编写程序,求一元二次方程ax²+bx+c=0的根(系数在程序中给定),并输出。
\u8fd9\u662f\u4e00\u4e2a\u6b63\u5f0f\u7684\u4e8c\u6b21\u65b9\u7a0b\u6c42\u89e3\u65b9\u7a0b\uff0c\u7528\u6765\u6c42\u89e3\u4e00\u4e2a\u4e8c\u6b21\u65b9\u7a0b\u65e0\u7b49\u5f0f\u7684\u65b9\u7a0b\u7b49\u7b97\u5f0f\u3002
\u4ee5\u4e0b\u662f\u4ee5JAVA\u8bed\u8a00\u7f16\u5199\u7684\u4ee3\u7801\uff1a
```java
import java.util.Scanner;
public class QuadraticEquationSolver {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the coefficients of the quadratic equation ax^2 + bx + c = 0:");
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
double discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double x1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double x2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The roots are real and different.");
System.out.println("x1 = " + x1);
System.out.println("x2 = " + x2);
} else if (discriminant == 0) {
double x = -b / (2 * a);
System.out.println("The roots are real and equal.");
System.out.println("x = " + x);
} else {
System.out.println("The roots are complex and different.");
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
System.out.println("x1 = " + realPart + "+" + imaginaryPart + "i");
System.out.println("x2 = " + realPart + "-" + imaginaryPart + "i");
}
}
}
```
\u8fd9\u4e2a\u7a0b\u5e8f\u53ef\u4ee5\u63d0\u4f9b\u7528\u6237\u8f93\u5165\u4e09\u4e2a\u6570\u5b57\uff0c\u5206\u522b\u4ee5a\u3001b\u548cc\u4f5c\u4e3a\u4e8c\u6b21\u65b9\u7a0b\u7684\u4e09\u4e2a\u7cfb\u6570\uff0c\u4e4b\u540e\u8ba1\u7b97\u51fa\u65b9\u7a0b\u7684\u6839\u3001\u65b9\u6839\u5f0f\u3001\u5e73\u65b9\u5f0f\u3001\u4e00\u5143\u4e8c\u6b21\u65b9\u7a0b\u89e3\u3001\u53cc\u6839\u5f0
阅读全文