设计一个复数类,实现两个复数的加减乘除运算。(复数:a+bi)使用java语言实现
时间: 2023-05-15 10:06:16 浏览: 55
好的,以下是Java语言实现的复数类,包括加减乘除运算:
```java
public class Complex {
private double real;
private double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public Complex add(Complex other) {
return new Complex(real + other.real, imag + other.imag);
}
public Complex subtract(Complex other) {
return new Complex(real - other.real, imag - other.imag);
}
public Complex multiply(Complex other) {
double newReal = real * other.real - imag * other.imag;
double newImag = real * other.imag + imag * other.real;
return new Complex(newReal, newImag);
}
public Complex divide(Complex other) {
double denominator = other.real * other.real + other.imag * other.imag;
double newReal = (real * other.real + imag * other.imag) / denominator;
double newImag = (imag * other.real - real * other.imag) / denominator;
return new Complex(newReal, newImag);
}
@Override
public String toString() {
return real + " + " + imag + "i";
}
}
```
使用示例:
```java
Complex a = new Complex(1, 2);
Complex b = new Complex(3, 4);
Complex c = a.add(b);
System.out.println(c); // 输出:4.0 + 6.0i
Complex d = a.subtract(b);
System.out.println(d); // 输出:-2.0 + -2.0i
Complex e = a.multiply(b);
System.out.println(e); // 输出:-5.0 + 10.0i
Complex f = a.divide(b);
System.out.println(f); // 输出:0.44 + -0.08i
```
希望能够帮到您!