java编写一元二次方程
时间: 2023-09-28 17:09:57 浏览: 103
java 一元二次方程
4星 · 用户满意度95%
以下是 Java 代码,用于解一元二次方程:
```java
import java.util.Scanner;
public class QuadraticEquationSolver {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of a: ");
double a = scanner.nextDouble();
System.out.print("Enter the value of b: ");
double b = scanner.nextDouble();
System.out.print("Enter the value of c: ");
double c = scanner.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");
}
}
}
```
使用这个代码,你可以输入一元二次方程的系数,然后程序将计算并输出方程的根。
阅读全文