设计一个复数类,实现两个复数的加减乘除运算。(复数:a+bi)使用java语言实现
时间: 2023-05-15 08:07:42 浏览: 250
好的,我可以回答这个问题。以下是一个简单的复数类的实现,包括加减乘除运算:
```java
public class ComplexNumber {
private double real;
private double imag;
public ComplexNumber(double real, double imag) {
this.real = real;
this.imag = imag;
}
public ComplexNumber add(ComplexNumber other) {
return new ComplexNumber(this.real + other.real, this.imag + other.imag);
}
public ComplexNumber subtract(ComplexNumber other) {
return new ComplexNumber(this.real - other.real, this.imag - other.imag);
}
public ComplexNumber multiply(ComplexNumber other) {
double real = this.real * other.real - this.imag * other.imag;
double imag = this.real * other.imag + this.imag * other.real;
return new ComplexNumber(real, imag);
}
public ComplexNumber divide(ComplexNumber other) {
double denominator = other.real * other.real + other.imag * other.imag;
double real = (this.real * other.real + this.imag * other.imag) / denominator;
double imag = (this.imag * other.real - this.real * other.imag) / denominator;
return new ComplexNumber(real, imag);
}
@Override
public String toString() {
return real + " + " + imag + "i";
}
}
```
使用示例:
```java
ComplexNumber a = new ComplexNumber(1, 2);
ComplexNumber b = new ComplexNumber(3, 4);
ComplexNumber c = a.add(b);
System.out.println(c); // 输出:4.0 + 6.0i
ComplexNumber d = a.subtract(b);
System.out.println(d); // 输出:-2.0 - 2.0i
ComplexNumber e = a.multiply(b);
System.out.println(e); // 输出:-5.0 + 10.0i
ComplexNumber f = a.divide(b);
System.out.println(f); // 输出:0.44 + 0.08i
```
希望这个实现能够满足您的需求。
阅读全文