计算一元二次方程根c
时间: 2024-06-15 14:08:14 浏览: 101
以下是使用Java代码计算一元二次方程根的示例[^1]:
```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 discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The equation has two real roots: " + root1 + " and " + root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("The equation has one real root: " + root);
} else {
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
System.out.println("The equation has two complex roots: " + realPart + " + " + imaginaryPart + "i and " + realPart + " - " + imaginaryPart + "i");
}
}
}
```
请注意,上述代码需要用户输入方程的系数a、b和c,并根据判别式的值来确定方程的根的类型。如果判别式大于0,则方程有两个实数根;如果判别式等于0,则方程有一个实数根;如果判别式小于0,则方程有两个复数根。
阅读全文