用java写求解一元二次方程
时间: 2024-03-09 21:40:25 浏览: 308
java一元二次方程求解
好的,以下是用Java求解一元二次方程的代码:
```java
import java.util.Scanner;
public class QuadraticEquation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a, b, c: ");
double a = input.nextDouble();
double b = input.nextDouble();
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 roots are " + root1 + " and " + root2); } else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("The root is " + root);
} else {
System.out.println("The equation has no real roots.");
}
}
}
```
阅读全文