JAVA编写一个求方程ax2+bx+c=0的根的程序,用3个方法分别求当b2-4ac大于零、等于零、和小于零时的方程的根。要求从主方法输入a,b,c的值并输出结果。
时间: 2024-03-11 11:46:44 浏览: 66
求根的JAVA程序
以下是JAVA编写的求方程ax2+bx+c=0的根的程序,用3个方法分别求当b2-4ac大于零、等于零、和小于零时的方程的根:
```
import java.util.Scanner;
public class QuadraticEquation {
// 求当b^2-4ac大于零时的方程的根
public static void solve1(double a, double b, double c) {
double delta = b * b - 4 * a * c;
if (delta > 0) {
double x1 = (-b + Math.sqrt(delta)) / (2 * a);
double x2 = (-b - Math.sqrt(delta)) / (2 * a);
System.out.println("方程的两个实根分别为:" + x1 + "和" + x2);
} else if (delta == 0) {
System.out.println("方程的唯一实根为:" + (-b / (2 * a)));
} else {
System.out.println("方程无实根!");
}
}
// 求当b^2-4ac等于零时的方程的根
public static void solve2(double a, double b, double c) {
double delta = b * b - 4 * a * c;
if (delta == 0) {
System.out.println("方程的唯一实根为:" + (-b / (2 * a)));
} else {
System.out.println("方程无实根!");
}
}
// 求当b^2-4ac小于零时的方程的根
public static void solve3(double a, double b, double c) {
double delta = b * b - 4 * a * c;
if (delta < 0) {
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-delta) / (2 * a);
System.out.println("方程的两个复根分别为:" + realPart + "+" + imaginaryPart + "i 和 " + realPart + "-" + imaginaryPart + "i");
} else {
System.out.println("方程无虚根!");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入方程的a、b、c值(空格分隔):");
double a = scanner.nextDouble();
double b = scanner.nextDouble();
double c = scanner.nextDouble();
System.out.println("方程为:" + a + "x^2 + " + b + "x + " + c + " = 0");
System.out.println("当b^2-4ac大于零时:");
solve1(a, b, c);
System.out.println("当b^2-4ac等于零时:");
solve2(a, b, c);
System.out.println("当b^2-4ac小于零时:");
solve3(a, b, c);
}
}
```
运行结果如下:
```
请输入方程的a、b、c值(空格分隔):1 2 1
方程为:1.0x^2 + 2.0x + 1.0 = 0
当b^2-4ac大于零时:
方程的唯一实根为:-1.0
当b^2-4ac等于零时:
方程的唯一实根为:-1.0
当b^2-4ac小于零时:
方程无虚根!
```
阅读全文