设计一个名为SolveEquation类来计算方程式ax**2+bx+c=0的平方根。该类包括: 私有数据域a、b和c表示3个系数;
时间: 2024-11-20 15:44:02 浏览: 17
设计一个名为`SolveEquation`的类用于计算二次方程`ax^2 + bx + c = 0`的根,可以按照以下步骤进行:
```java
public class SolveEquation {
// 私有数据域,代表二次方程的系数
private double a;
private double b;
private double c;
// 构造函数,接受三个系数作为参数
public SolveEquation(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
// 计算判别式,判断方程是否有实数解
private double discriminant() {
return Math.pow(b, 2) - 4 * a * c;
}
// 应用公式求解两个根(如果存在)
public ComplexNumber[] solve() {
double discriminantValue = discriminant();
if (discriminantValue > 0) { // 有两个实数根
double root1 = (-b + Math.sqrt(discriminantValue)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminantValue)) / (2 * a);
return new ComplexNumber[]{new ComplexNumber(root1), new ComplexNumber(root2)};
} else if (discriminantValue == 0) { // 有一个实数根(重复)
double root = -b / (2 * a);
return new ComplexNumber[]{new ComplexNumber(root)};
} else { // 无实数根,返回复数根
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-discriminantValue) / (2 * a);
return new ComplexNumber[]{new ComplexNumber(realPart, imaginaryPart), new ComplexNumber(realPart, -imaginaryPart)};
}
}
// 内部类ComplexNumber用于存储复数
private static class ComplexNumber {
private final double real;
private final double imag;
public ComplexNumber(double real, double imag) {
this.real = real;
this.imag = imag;
}
// ... 其他复数操作方法省略
}
}
```
阅读全文