java求一元二次方程+y=ax2+bx+c+的实数根。
时间: 2023-11-21 09:55:29 浏览: 118
以下是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.");
}
}
}
```
用户需要输入方程的系数a、b、c,程序会根据判别式的值来输出方程的实数根。如果判别式大于0,则方程有两个实数根;如果判别式等于0,则方程有一个实数根;如果判别式小于0,则方程无实数根。
阅读全文