java实现复数的加减乘除(附完整源码)
时间: 2023-11-09 19:07:43 浏览: 42
以下是Java实现复数的加减乘除的完整源码,包括复数类和测试代码:
```java
public class Complex {
private double real;
private double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public double getReal() {
return real;
}
public double getImag() {
return imag;
}
public Complex add(Complex other) {
double real = this.real + other.real;
double imag = this.imag + other.imag;
return new Complex(real, imag);
}
public Complex subtract(Complex other) {
double real = this.real - other.real;
double imag = this.imag - other.imag;
return new Complex(real, imag);
}
public Complex multiply(Complex other) {
double real = this.real * other.real - this.imag * other.imag;
double imag = this.real * other.imag + this.imag * other.real;
return new Complex(real, imag);
}
public Complex divide(Complex other) {
double real = (this.real * other.real + this.imag * other.imag) / (other.real * other.real + other.imag * other.imag);
double imag = (this.imag * other.real - this.real * other.imag) / (other.real * other.real + other.imag * other.imag);
return new Complex(real, imag);
}
@Override
public String toString() {
return "(" + real + " + " + imag + "i)";
}
}
```
测试代码:
```java
public class ComplexTest {
public static void main(String[] args) {
Complex c1 = new Complex(2, 3);
Complex c2 = new Complex(4, -5);
System.out.println("c1 = " + c1);
System.out.println("c2 = " + c2);
Complex sum = c1.add(c2);
System.out.println("c1 + c2 = " + sum);
Complex diff = c1.subtract(c2);
System.out.println("c1 - c2 = " + diff);
Complex product = c1.multiply(c2);
System.out.println("c1 * c2 = " + product);
Complex quotient = c1.divide(c2);
System.out.println("c1 / c2 = " + quotient);
}
}
```
输出结果:
```
c1 = (2.0 + 3.0i)
c2 = (4.0 + -5.0i)
c1 + c2 = (6.0 + -2.0i)
c1 - c2 = (-2.0 + 8.0i)
c1 * c2 = (23.0 + 2.0i)
c1 / c2 = (-0.24 + 0.52i)
```