java复数类java程序如何编写

复数类实现方法
在Java中实现复数类需要定义复数的基本属性和运算方法。复数通常由实部和虚部组成,支持加减乘除等运算。

public class Complex {
private double real; // 实部
private double imaginary; // 虚部
// 构造函数
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
// 获取实部
public double getReal() {
return real;
}
// 获取虚部
public double getImaginary() {
return imaginary;
}
// 复数加法
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imaginary + other.imaginary);
}
// 复数减法
public Complex subtract(Complex other) {
return new Complex(this.real - other.real, this.imaginary - other.imaginary);
}
// 复数乘法
public Complex multiply(Complex other) {
double newReal = this.real * other.real - this.imaginary * other.imaginary;
double newImaginary = this.real * other.imaginary + this.imaginary * other.real;
return new Complex(newReal, newImaginary);
}
// 复数除法
public Complex divide(Complex other) {
double denominator = other.real * other.real + other.imaginary * other.imaginary;
double newReal = (this.real * other.real + this.imaginary * other.imaginary) / denominator;
double newImaginary = (this.imaginary * other.real - this.real * other.imaginary) / denominator;
return new Complex(newReal, newImaginary);
}
// 复数的模
public double modulus() {
return Math.sqrt(real * real + imaginary * imaginary);
}
// 复数的共轭
public Complex conjugate() {
return new Complex(real, -imaginary);
}
// 重写toString方法
@Override
public String toString() {
if (imaginary >= 0) {
return real + " + " + imaginary + "i";
} else {
return real + " - " + (-imaginary) + "i";
}
}
}
使用示例
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(3, 4);
Complex c2 = new Complex(1, -2);
System.out.println("c1 = " + c1);
System.out.println("c2 = " + c2);
System.out.println("c1 + c2 = " + c1.add(c2));
System.out.println("c1 - c2 = " + c1.subtract(c2));
System.out.println("c1 * c2 = " + c1.multiply(c2));
System.out.println("c1 / c2 = " + c1.divide(c2));
System.out.println("|c1| = " + c1.modulus());
System.out.println("c1的共轭复数 = " + c1.conjugate());
}
}
扩展功能
复数类可以根据需要扩展更多功能,例如极坐标表示、指数形式、对数运算等。对于科学计算,还可以实现更复杂的数学函数支持。
// 极坐标表示
public double getArgument() {
return Math.atan2(imaginary, real);
}
// 指数形式
public String toExponentialForm() {
return modulus() + " * e^(" + getArgument() + "i)";
}






