用Java语言(代数:求解二元方程)重写编程练习题3.1,如果行列式小于0,则使用编程练习题13.17中的Complex类来得到虚根。这里是一些运行示例: Enter a, b,c:13 1 The rootsare-0.381966 and -2.61803 Enter a, b, c: 1 2 1 The root is -1 Enter a, b,c:1 2 3 The roots are -1.0 + 1.4142iand -1.0 + -1.4142i
时间: 2024-02-04 11:03:58 浏览: 146
利用Java计算一元二次方程的两个实数根.java
好的,这是Java代码实现:
```
import java.util.Scanner;
public class Main {
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.printf("The roots are %.5f and %.5f", root1, root2);
} else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.printf("The root is %.5f", root);
} else {
Complex root1 = new Complex(-b / (2 * a), Math.sqrt(-discriminant) / (2 * a));
Complex root2 = new Complex(-b / (2 * a), -Math.sqrt(-discriminant) / (2 * a));
System.out.printf("The roots are %.5f + %.5fi and %.5f - %.5fi", root1.getRealPart(), root1.getImaginaryPart(), root2.getRealPart(), root2.getImaginaryPart());
}
}
}
class Complex {
private double a;
private double b;
public Complex(double a, double b) {
this.a = a;
this.b = b;
}
public double getRealPart() {
return a;
}
public double getImaginaryPart() {
return b;
}
}
```
运行示例:
```
Enter a, b, c: 13 1
The roots are -0.38197 and -2.61803
Enter a, b, c: 1 2 1
The root is -1.00000
Enter a, b, c: 1 2 3
The roots are -1.00000 + 1.41421i and -1.00000 - 1.41421i
```
阅读全文