用java编写一个复数类,能进行复数的加、减、乘和求模运算,其中,加、减、乘运算提供了两种形式,一种是对象方法,将当前复数与参数中的复数进行运算,返回一个新的复数对象,另一种是静态方法,将两个参数代表的复数进行运算。另外设计1oStringO描述复数对象,通过实际数据测试类的设计。
时间: 2024-02-25 17:58:48 浏览: 42
好的,以下是Java代码实现:
```java
public class Complex {
private double real;
double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 加法,对象方法
public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imag + other.imag);
}
// 加法,静态方法
public static Complex add(Complex c1, Complex c2) {
return new Complex(c1.real + c2.real, c1.imag + c2.imag);
}
// 减法,对象方法
public Complex sub(Complex other) {
return new Complex(this.real - other.real, this.imag - other.imag);
}
// 减法,静态方法
public static Complex sub(Complex c1, Complex c2) {
return new Complex(c1.real - c2.real, c1.imag - c2.imag);
}
// 乘法,对象方法
public Complex mul(Complex other) {
return new Complex(this.real * other.real - this.imag * other.imag,
this.real * other.imag + this.imag * other.real);
}
// 乘法,静态方法
public static Complex mul(Complex c1, Complex c2) {
return new Complex(c1.real * c2.real - c1.imag * c2.imag,
c1.real * c2.imag + c1.imag * c2.real);
}
// 模运算
public double modulus() {
return Math.sqrt(this.real * this.real + this.imag * this.imag);
}
// 描述复数对象
public String toString() {
if (imag < 0) {
return real + " - " + (-imag) + "i";
} else {
return real + " + " + imag + "i";
}
}
}
```
可以通过以下代码进行测试:
```java
public class TestComplex {
public static void main(String[] args) {
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(2, 1);
// 加法
Complex c3 = c1.add(c2);
Complex c4 = Complex.add(c1, c2);
System.out.println(c3); // 3.0 + 3.0i
System.out.println(c4); // 3.0 + 3.0i
// 减法
Complex c5 = c1.sub(c2);
Complex c6 = Complex.sub(c1, c2);
System.out.println(c5); // -1.0 + 1.0i
System.out.println(c6); // -1.0 + 1.0i
// 乘法
Complex c7 = c1.mul(c2);
Complex c8 = Complex.mul(c1, c2);
System.out.println(c7); // 0.0 + 5.0i
System.out.println(c8); // 0.0 + 5.0i
// 模运算
double mod1 = c1.modulus();
double mod2 = c2.modulus();
System.out.println(mod1); // 2.23606797749979
System.out.println(mod2); // 2.23606797749979
}
}
```